mirror of
https://github.com/microsoft/TypeScript.git
synced 2025-11-18 17:21:48 +00:00
Merge branch 'main' into fix44572
# Conflicts: # src/compiler/checker.ts
This commit is contained in:
@@ -7,7 +7,13 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"terminal.integrated.shell.linux": "/bin/bash"
|
||||
"terminal.integrated.defaultProfile.linux": "bash",
|
||||
"terminal.integrated.profiles.linux": {
|
||||
"bash": {
|
||||
"path": "/bin/bash",
|
||||
"icon": "terminal-bash",
|
||||
},
|
||||
},
|
||||
},
|
||||
"extensions": [
|
||||
"dbaeumer.vscode-eslint"
|
||||
|
||||
@@ -10,4 +10,7 @@ ahejlsberg
|
||||
amcasey
|
||||
jessetrinity
|
||||
minestarks
|
||||
uniqueiniquity
|
||||
armanio123
|
||||
gabritto
|
||||
jakebailey
|
||||
DanielRosenwasser
|
||||
|
||||
@@ -9,6 +9,13 @@ Please verify that:
|
||||
|
||||
Refer to CONTRIBUTING.MD for more details.
|
||||
https://github.com/Microsoft/TypeScript/blob/main/CONTRIBUTING.md
|
||||
|
||||
** Please don't send typo fixes! **
|
||||
Please don't send a PR solely for the purpose of fixing a typo, unless that
|
||||
typo truly hurts understanding of the text. Each PR represents work for the
|
||||
maintainers, and that work should provide commensurate value.
|
||||
|
||||
If you're interested in sending a PR, the issue tracker has many issues marked `help wanted`.
|
||||
-->
|
||||
|
||||
Fixes #
|
||||
|
||||
@@ -20,6 +20,7 @@ jobs:
|
||||
git config user.email "typescriptbot@microsoft.com"
|
||||
git config user.name "TypeScript Bot"
|
||||
npm install
|
||||
git rm -r --quiet tests/baselines/reference :^tests/baselines/reference/docker :^tests/baselines/reference/user
|
||||
gulp runtests-parallel --ci --fix || true
|
||||
gulp baseline-accept
|
||||
git add ./src
|
||||
|
||||
@@ -16,7 +16,7 @@ jobs:
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
node-version: [10.x, 12.x, 14.x]
|
||||
node-version: [12.x, 14.x, 16.x]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# Ensures that repos which are related to TypeScript but may not have regular commits
|
||||
# have their GitHub Actions scheduled jobs still active due to the 6 week timeout
|
||||
# on OSS repos. This has already triggered a few times with microsoft/TypeScript-Make-Monaco-Builds
|
||||
# so, better to automate keeping on top of it.
|
||||
|
||||
name: Related Repo Commit Bumps
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# Monthly, https://crontab.guru/#0_0_*_1-12_*
|
||||
- cron: '0 0 1 * *'
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Configure git
|
||||
run: |
|
||||
git config --global user.email "typescriptbot@microsoft.com"
|
||||
git config --global user.name "TypeScript Bot"
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
repository: 'microsoft/TypeScript-Website'
|
||||
path: 'ts-site'
|
||||
|
||||
- name: Push Commit to TS Website
|
||||
run: |
|
||||
cd ts-site
|
||||
git commit --allow-empty -m "Monthly Bump"
|
||||
git config --unset-all http.https://github.com/.extraheader
|
||||
git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Website.git
|
||||
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
repository: 'microsoft/TypeScript-Make-Monaco-Builds'
|
||||
path: 'monaco-builds'
|
||||
|
||||
- name: Push Commit to TS Make Monaco Builds
|
||||
run: |
|
||||
cd monaco-builds
|
||||
git commit --allow-empty -m "Monthly Bump"
|
||||
git config --unset-all http.https://github.com/.extraheader
|
||||
git push https://${{ secrets.TS_BOT_GITHUB_TOKEN }}@github.com/microsoft/TypeScript-Make-Monaco-Builds.git
|
||||
Vendored
+2
-10
@@ -48,11 +48,7 @@
|
||||
"outFiles": [
|
||||
"${workspaceRoot}/built/local/run.js"
|
||||
],
|
||||
|
||||
// NOTE: To use this, you must switch the "type" above to "pwa-node". You may also need to follow the instructions
|
||||
// here: https://github.com/microsoft/vscode-js-debug#nightly-extension to use the js-debug nightly until
|
||||
// this feature is shipping in insiders or to a release:
|
||||
// "customDescriptionGenerator": "'__tsDebuggerDisplay' in this ? this.__tsDebuggerDisplay(defaultValue) : defaultValue"
|
||||
"customDescriptionGenerator": "'__tsDebuggerDisplay' in this ? this.__tsDebuggerDisplay(defaultValue) : defaultValue",
|
||||
},
|
||||
{
|
||||
// See: https://github.com/microsoft/TypeScript/wiki/Debugging-Language-Service-in-VS-Code
|
||||
@@ -60,11 +56,7 @@
|
||||
"request": "attach",
|
||||
"name": "Attach to VS Code TS Server via Port",
|
||||
"processId": "${command:PickProcess}",
|
||||
|
||||
// NOTE: To use this, you must switch the "type" above to "pwa-node". You may also need to follow the instructions
|
||||
// here: https://github.com/microsoft/vscode-js-debug#nightly-extension to use the js-debug nightly until
|
||||
// this feature is shipping in insiders or to a release:
|
||||
// "customDescriptionGenerator": "'__tsDebuggerDisplay' in this ? this.__tsDebuggerDisplay(defaultValue) : defaultValue"
|
||||
"customDescriptionGenerator": "'__tsDebuggerDisplay' in this ? this.__tsDebuggerDisplay(defaultValue) : defaultValue",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Vendored
+2
-5
@@ -2,10 +2,7 @@
|
||||
// contents into your existing settings.
|
||||
{
|
||||
"eslint.validate": [
|
||||
{
|
||||
"language": "typescript",
|
||||
"autoFix": true
|
||||
}
|
||||
"typescript"
|
||||
],
|
||||
"eslint.options": {
|
||||
"rulePaths": ["./scripts/eslint/built/rules/"],
|
||||
@@ -16,4 +13,4 @@
|
||||
|
||||
// To use the locally built compiler, after 'npm run build':
|
||||
// "typescript.tsdk": "built/local"
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ Some search tips:
|
||||
## 3. Do you have a question?
|
||||
|
||||
The issue tracker is for **issues**, in other words, bugs and suggestions.
|
||||
If you have a *question*, please use [Stack Overflow](http://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources.
|
||||
If you have a *question*, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/typescript), [Gitter](https://gitter.im/Microsoft/TypeScript), your favorite search engine, or other resources.
|
||||
Due to increased traffic, we can no longer answer questions in the issue tracker.
|
||||
|
||||
## 4. Did you find a bug?
|
||||
|
||||
@@ -130,7 +130,7 @@
|
||||
"Add_await_to_initializer_for_0_95084": "将 \"await\" 添加到 \"{0}\" 的初始值设定项",
|
||||
"Add_await_to_initializers_95089": "将 \"await\" 添加到初始值设定项",
|
||||
"Add_braces_to_arrow_function_95059": "向箭头函数添加大括号",
|
||||
"Add_class_tag_95102": "添加“@类”标记",
|
||||
"Add_class_tag_95102": "添加“@class”标记",
|
||||
"Add_const_to_all_unresolved_variables_95082": "将 \"const\" 添加到所有未解析变量",
|
||||
"Add_const_to_unresolved_variable_95081": "将 \"const\" 添加到未解析的变量",
|
||||
"Add_default_import_0_to_existing_import_declaration_from_1_90033": "将默认导入 \"{0}\" 从 \"{1}\" 添加到现有导入声明。",
|
||||
@@ -154,7 +154,7 @@
|
||||
"Add_parameter_name_90034": "添加参数名称",
|
||||
"Add_qualifier_to_all_unresolved_variables_matching_a_member_name_95037": "将限定符添加到匹配成员名称的所有未解析变量",
|
||||
"Add_this_parameter_95104": "添加“此”参数。",
|
||||
"Add_this_tag_95103": "添加“@此”标记",
|
||||
"Add_this_tag_95103": "添加“@this”标记",
|
||||
"Add_to_all_uncalled_decorators_95044": "将 \"()\" 添加到所有未调用的修饰器",
|
||||
"Add_ts_ignore_to_all_error_messages_95042": "将 \"@ts-ignore\" 添加到所有错误消息",
|
||||
"Add_undefined_to_a_type_when_accessed_using_an_index_6674": "使用索引访问时,将 “undefined” 添加到类型。",
|
||||
@@ -1784,4 +1784,4 @@
|
||||
"with_statements_are_not_allowed_in_strict_mode_1101": "严格模式下不允许使用 \"with\" 语句。",
|
||||
"yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_t_7057": "\"yield\" 表达式隐式导致 \"any\" 类型,因为它的包含生成器缺少返回类型批注。",
|
||||
"yield_expressions_cannot_be_used_in_a_parameter_initializer_2523": "不能在参数初始化表达式中使用 \"yield\" 表达式。"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+261
-253
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "typescript",
|
||||
"version": "4.5.0",
|
||||
"version": "4.7.0",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
@@ -279,9 +279,9 @@
|
||||
}
|
||||
},
|
||||
"@octokit/auth-token": {
|
||||
"version": "2.4.5",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz",
|
||||
"integrity": "sha512-BpGYsPgJt05M7/L/5FoE1PiAbdxXFZkX/3kDYcsvd1v6UhlnE5e96dTDr0ezX/EFwciQxf3cNV0loipsURU+WA==",
|
||||
"version": "2.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.5.0.tgz",
|
||||
"integrity": "sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@octokit/types": "^6.0.3"
|
||||
@@ -325,18 +325,18 @@
|
||||
}
|
||||
},
|
||||
"@octokit/openapi-types": {
|
||||
"version": "10.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-10.1.1.tgz",
|
||||
"integrity": "sha512-ygp/6r25Ezb1CJuVMnFfOsScEtPF0zosdTJDZ7mZ+I8IULl7DP1BS5ZvPRwglcarGPXOvS5sHdR0bjnVDDfQdQ==",
|
||||
"version": "11.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-11.2.0.tgz",
|
||||
"integrity": "sha512-PBsVO+15KSlGmiI8QAzaqvsNlZlrDlyAJYcrXBCvVUxCp7VnXjkwPoFHgjEJXx3WF9BAwkA6nfCUA7i9sODzKA==",
|
||||
"dev": true
|
||||
},
|
||||
"@octokit/plugin-paginate-rest": {
|
||||
"version": "2.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.16.0.tgz",
|
||||
"integrity": "sha512-8YYzALPMvEZ35kgy5pdYvQ22Roz+BIuEaedO575GwE2vb/ACDqQn0xQrTJR4tnZCJn7pi8+AWPVjrFDaERIyXQ==",
|
||||
"version": "2.17.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.17.0.tgz",
|
||||
"integrity": "sha512-tzMbrbnam2Mt4AhuyCHvpRkS0oZ5MvwwcQPYGtMv4tUa5kkzG58SVB0fcsLulOZQeRnOgdkZWkRUiyBlh0Bkyw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@octokit/types": "^6.26.0"
|
||||
"@octokit/types": "^6.34.0"
|
||||
}
|
||||
},
|
||||
"@octokit/plugin-request-log": {
|
||||
@@ -346,26 +346,26 @@
|
||||
"dev": true
|
||||
},
|
||||
"@octokit/plugin-rest-endpoint-methods": {
|
||||
"version": "5.10.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.10.1.tgz",
|
||||
"integrity": "sha512-Rf1iMl40I0dIxjh1g32qZ6Ym/uT8QWZMm2vYGG5Vi8SX1MwZvbuxEGXYgmzTUWSD3PYWSLilE2+4L8kmdLGTMg==",
|
||||
"version": "5.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.13.0.tgz",
|
||||
"integrity": "sha512-uJjMTkN1KaOIgNtUPMtIXDOjx6dGYysdIFhgA52x4xSadQCz3b/zJexvITDVpANnfKPW/+E0xkOvLntqMYpviA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@octokit/types": "^6.27.0",
|
||||
"@octokit/types": "^6.34.0",
|
||||
"deprecation": "^2.3.1"
|
||||
}
|
||||
},
|
||||
"@octokit/request": {
|
||||
"version": "5.6.1",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.1.tgz",
|
||||
"integrity": "sha512-Ls2cfs1OfXaOKzkcxnqw5MR6drMA/zWX/LIS/p8Yjdz7QKTPQLMsB3R+OvoxE6XnXeXEE2X7xe4G4l4X0gRiKQ==",
|
||||
"version": "5.6.3",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz",
|
||||
"integrity": "sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@octokit/endpoint": "^6.0.1",
|
||||
"@octokit/request-error": "^2.1.0",
|
||||
"@octokit/types": "^6.16.1",
|
||||
"is-plain-object": "^5.0.0",
|
||||
"node-fetch": "^2.6.1",
|
||||
"node-fetch": "^2.6.7",
|
||||
"universal-user-agent": "^6.0.0"
|
||||
}
|
||||
},
|
||||
@@ -381,24 +381,24 @@
|
||||
}
|
||||
},
|
||||
"@octokit/rest": {
|
||||
"version": "18.10.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.10.0.tgz",
|
||||
"integrity": "sha512-esHR5OKy38bccL/sajHqZudZCvmv4yjovMJzyXlphaUo7xykmtOdILGJ3aAm0mFHmMLmPFmDMJXf39cAjNJsrw==",
|
||||
"version": "18.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.12.0.tgz",
|
||||
"integrity": "sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@octokit/core": "^3.5.1",
|
||||
"@octokit/plugin-paginate-rest": "^2.16.0",
|
||||
"@octokit/plugin-paginate-rest": "^2.16.8",
|
||||
"@octokit/plugin-request-log": "^1.0.4",
|
||||
"@octokit/plugin-rest-endpoint-methods": "^5.9.0"
|
||||
"@octokit/plugin-rest-endpoint-methods": "^5.12.0"
|
||||
}
|
||||
},
|
||||
"@octokit/types": {
|
||||
"version": "6.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.27.0.tgz",
|
||||
"integrity": "sha512-ha27f8DToxXBPEJdzHCCuqpw7AgKfjhWGdNf3yIlBAhAsaexBXTfWw36zNSsncALXGvJq4EjLy1p3Wz45Aqb4A==",
|
||||
"version": "6.34.0",
|
||||
"resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.34.0.tgz",
|
||||
"integrity": "sha512-s1zLBjWhdEI2zwaoSgyOFoKSl109CUcVBCc7biPJ3aAf6LGLU6szDvi31JPU7bxfla2lqfhjbbg/5DdFNxOwHw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@octokit/openapi-types": "^10.1.0"
|
||||
"@octokit/openapi-types": "^11.2.0"
|
||||
}
|
||||
},
|
||||
"@types/browserify": {
|
||||
@@ -412,9 +412,9 @@
|
||||
}
|
||||
},
|
||||
"@types/chai": {
|
||||
"version": "4.2.21",
|
||||
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.2.21.tgz",
|
||||
"integrity": "sha512-yd+9qKmJxm496BOV9CMNaey8TWsikaZOwMRwPHQIjcOJM9oV+fi9ZMNw3JsVnbEEbo2gRTDnGEBv8pjyn67hNg==",
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.0.tgz",
|
||||
"integrity": "sha512-/ceqdqeRraGolFTcfoXNiqjyQhZzbINDngeoAq9GoHa8PPK1yNzTaxWjA6BFWp5Ua9JpXEMSS4s5i9tS0hOJtw==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/convert-source-map": {
|
||||
@@ -430,9 +430,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"@types/glob": {
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.1.4.tgz",
|
||||
"integrity": "sha512-w+LsMxKyYQm347Otw+IfBXOv9UWVjpHpCDdbBMt8Kz/xbvCYNjP+0qPh91Km3iKfSRLBB0P7fAMf0KHrPu+MyA==",
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz",
|
||||
"integrity": "sha512-ZUxbzKl0IfJILTS6t7ip5fQQM/J3TJYubDm3nMbgubNNYS62eXeUpoLUC8/7fJNiFYHTrGPQn7hspDUzIHX3UA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@types/minimatch": "*",
|
||||
@@ -664,9 +664,9 @@
|
||||
}
|
||||
},
|
||||
"@types/mocha": {
|
||||
"version": "9.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-9.0.0.tgz",
|
||||
"integrity": "sha512-scN0hAWyLVAvLR9AyW7HoFF5sJZglyBsbPuHO4fv7JRvfmPBMfp1ozWqOf/e4wwPNxezBZXRfWzMb6iFLgEVRA==",
|
||||
"version": "9.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-9.1.0.tgz",
|
||||
"integrity": "sha512-QCWHkbMv4Y5U9oW10Uxbr45qMMSzl4OzijsozynUAgx3kEHUdXB00udx2dWDQ7f2TU2a2uuiFaRZjCe3unPpeg==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/ms": {
|
||||
@@ -676,9 +676,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"@types/node": {
|
||||
"version": "16.9.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.9.0.tgz",
|
||||
"integrity": "sha512-nmP+VR4oT0pJUPFbKE4SXj3Yb4Q/kz3M9dSAO1GGMebRKWHQxLfDNmU/yh3xxCJha3N60nQ/JwXWwOE/ZSEVag==",
|
||||
"version": "17.0.18",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.18.tgz",
|
||||
"integrity": "sha512-eKj4f/BsN/qcculZiRSujogjvp5O/k4lOW5m35NopjZM/QwLOR075a8pJW5hD+Rtdm2DaCVPENS6KtSQnUD6BA==",
|
||||
"dev": true
|
||||
},
|
||||
"@types/node-fetch": {
|
||||
@@ -1316,9 +1316,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"async": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-3.2.1.tgz",
|
||||
"integrity": "sha512-XdD5lRO/87udXCMC9meWdYiR+Nq6ZjUfXidViUZGu2F1MO4T3XwZ1et0hb2++BgLfhyJwy44BGB/yx80ABx8hg==",
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/async/-/async-3.2.3.tgz",
|
||||
"integrity": "sha512-spZRyzKL5l5BZQrr/6m/SqFdBN0q3OCI0f9rjfBzCMBIP4p75P620rR3gTmaksNOhmzgdxcaxdNfMy6anrbM0g==",
|
||||
"dev": true
|
||||
},
|
||||
"async-done": {
|
||||
@@ -1646,21 +1646,22 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"resolve": {
|
||||
"version": "1.20.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz",
|
||||
"integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==",
|
||||
"version": "1.22.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz",
|
||||
"integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"is-core-module": "^2.2.0",
|
||||
"path-parse": "^1.0.6"
|
||||
"is-core-module": "^2.8.1",
|
||||
"path-parse": "^1.0.7",
|
||||
"supports-preserve-symlinks-flag": "^1.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"is-core-module": {
|
||||
"version": "2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.6.0.tgz",
|
||||
"integrity": "sha512-wShG8vs60jKfPWpF2KZRaAtvt3a20OAn7+IJ6hLPECpSABLcKtFKTTI4ZtH5QcBruBHlq+WsdHWyz0BCZW7svQ==",
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz",
|
||||
"integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"has": "^1.0.3"
|
||||
@@ -1822,9 +1823,9 @@
|
||||
}
|
||||
},
|
||||
"cached-path-relative": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/cached-path-relative/-/cached-path-relative-1.0.2.tgz",
|
||||
"integrity": "sha512-5r2GqsoEb4qMTTN9J+WzXfjov+hjxT+j3u5K+kIVNIwAd99DLCJE9pBIMP1qVeybV6JiijL385Oz0DcYxfbOIg==",
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/cached-path-relative/-/cached-path-relative-1.1.0.tgz",
|
||||
"integrity": "sha512-WF0LihfemtesFcJgO7xfOoOcnWzY/QHR4qeDqV44jPU3HTI54+LnfXK3SA27AVVGCdZFgjjFFaqUA9Jx7dMJZA==",
|
||||
"dev": true
|
||||
},
|
||||
"call-bind": {
|
||||
@@ -1850,15 +1851,16 @@
|
||||
"dev": true
|
||||
},
|
||||
"chai": {
|
||||
"version": "4.3.4",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-4.3.4.tgz",
|
||||
"integrity": "sha512-yS5H68VYOCtN1cjfwumDSuzn/9c+yza4f3reKXlE5rUg7SFcCEy90gJvydNgOYtblyf4Zi6jIWRnXOgErta0KA==",
|
||||
"version": "4.3.6",
|
||||
"resolved": "https://registry.npmjs.org/chai/-/chai-4.3.6.tgz",
|
||||
"integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"assertion-error": "^1.1.0",
|
||||
"check-error": "^1.0.2",
|
||||
"deep-eql": "^3.0.1",
|
||||
"get-func-name": "^2.0.0",
|
||||
"loupe": "^2.3.1",
|
||||
"pathval": "^1.1.1",
|
||||
"type-detect": "^4.0.5"
|
||||
}
|
||||
@@ -2173,24 +2175,13 @@
|
||||
"dev": true
|
||||
},
|
||||
"copy-props": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/copy-props/-/copy-props-2.0.4.tgz",
|
||||
"integrity": "sha512-7cjuUME+p+S3HZlbllgsn2CDwS+5eCCX16qBgNC4jgSTf49qR1VKy/Zhl400m0IQXl/bPGEVqncgUUMjrr4s8A==",
|
||||
"version": "2.0.5",
|
||||
"resolved": "https://registry.npmjs.org/copy-props/-/copy-props-2.0.5.tgz",
|
||||
"integrity": "sha512-XBlx8HSqrT0ObQwmSzM7WE5k8FxTV75h1DX1Z3n6NhQ/UYYAvInWYmG06vFt7hQZArE2fuO62aihiWIVQwh1sw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"each-props": "^1.3.0",
|
||||
"is-plain-object": "^2.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"is-plain-object": {
|
||||
"version": "2.0.4",
|
||||
"resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz",
|
||||
"integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"isobject": "^3.0.1"
|
||||
}
|
||||
}
|
||||
"each-props": "^1.3.2",
|
||||
"is-plain-object": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"core-util-is": {
|
||||
@@ -2860,6 +2851,16 @@
|
||||
"v8-compile-cache": "^2.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-styles": "^4.1.0",
|
||||
"supports-color": "^7.1.0"
|
||||
}
|
||||
},
|
||||
"cross-spawn": {
|
||||
"version": "7.0.3",
|
||||
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz",
|
||||
@@ -2982,6 +2983,18 @@
|
||||
"requires": {
|
||||
"chalk": "^4.1.0",
|
||||
"plur": "^4.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"chalk": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
|
||||
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-styles": "^4.1.0",
|
||||
"supports-color": "^7.1.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"eslint-import-resolver-node": {
|
||||
@@ -3392,15 +3405,12 @@
|
||||
}
|
||||
},
|
||||
"fancy-log": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.3.tgz",
|
||||
"integrity": "sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw==",
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-2.0.0.tgz",
|
||||
"integrity": "sha512-9CzxZbACXMUXW13tS0tI8XsGGmxWzO2DmYrGuBJOJ8k8q2K7hwfJA5qHjuPPe8wtsco33YR9wc+Rlr5wYFvhSA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-gray": "^0.1.1",
|
||||
"color-support": "^1.1.3",
|
||||
"parse-node-version": "^1.0.0",
|
||||
"time-stamp": "^1.0.0"
|
||||
"color-support": "^1.1.3"
|
||||
}
|
||||
},
|
||||
"fast-deep-equal": {
|
||||
@@ -3788,9 +3798,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"glob": {
|
||||
"version": "7.1.7",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.1.7.tgz",
|
||||
"integrity": "sha512-OvD9ENzPLbegENnYP5UUfJIirTg4+XwMWGaQfQTY0JenxNvvIKP3U3/tAQSPIu/lHxXYSZmpXlUHeqAIdKzBLQ==",
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz",
|
||||
"integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"fs.realpath": "^1.0.0",
|
||||
@@ -3961,6 +3971,20 @@
|
||||
"semver-greatest-satisfied-range": "^1.1.0",
|
||||
"v8flags": "^3.2.0",
|
||||
"yargs": "^7.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"fancy-log": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/fancy-log/-/fancy-log-1.3.3.tgz",
|
||||
"integrity": "sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-gray": "^0.1.1",
|
||||
"color-support": "^1.1.3",
|
||||
"parse-node-version": "^1.0.0",
|
||||
"time-stamp": "^1.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4694,6 +4718,12 @@
|
||||
"is-unc-path": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"is-shared-array-buffer": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.1.tgz",
|
||||
"integrity": "sha512-IU0NmyknYZN0rChcKhRO1X8LYz5Isj/Fsqh8NJOSf+N/hCOTwy29F32Ik7a+QszE63IdvmwdTPDd6cZ5pg4cwA==",
|
||||
"dev": true
|
||||
},
|
||||
"is-string": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/is-string/-/is-string-1.0.5.tgz",
|
||||
@@ -4723,9 +4753,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"es-abstract": {
|
||||
"version": "1.18.6",
|
||||
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.6.tgz",
|
||||
"integrity": "sha512-kAeIT4cku5eNLNuUKhlmtuk1/TRZvQoYccn6TO0cSVdf1kzB0T7+dYuVK9MWM7l+/53W2Q8M7N2c6MQvhXFcUQ==",
|
||||
"version": "1.19.1",
|
||||
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.19.1.tgz",
|
||||
"integrity": "sha512-2vJ6tjA/UfqLm2MPs7jxVybLoB8i1t1Jd9R3kISld20sIxPcTbLuggQOUxeWeAvIUkduv/CfMjuh4WmiXr2v9w==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"call-bind": "^1.0.2",
|
||||
@@ -4739,7 +4769,9 @@
|
||||
"is-callable": "^1.2.4",
|
||||
"is-negative-zero": "^2.0.1",
|
||||
"is-regex": "^1.1.4",
|
||||
"is-shared-array-buffer": "^1.0.1",
|
||||
"is-string": "^1.0.7",
|
||||
"is-weakref": "^1.0.1",
|
||||
"object-inspect": "^1.11.0",
|
||||
"object-keys": "^1.1.1",
|
||||
"object.assign": "^4.1.2",
|
||||
@@ -4761,9 +4793,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"is-negative-zero": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz",
|
||||
"integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==",
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz",
|
||||
"integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==",
|
||||
"dev": true
|
||||
},
|
||||
"is-regex": {
|
||||
@@ -4786,9 +4818,9 @@
|
||||
}
|
||||
},
|
||||
"object-inspect": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz",
|
||||
"integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==",
|
||||
"version": "1.12.0",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.0.tgz",
|
||||
"integrity": "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==",
|
||||
"dev": true
|
||||
},
|
||||
"object.assign": {
|
||||
@@ -4852,6 +4884,15 @@
|
||||
"integrity": "sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao=",
|
||||
"dev": true
|
||||
},
|
||||
"is-weakref": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.0.2.tgz",
|
||||
"integrity": "sha512-qctsuLZmIQ0+vSSMfoVvyFe2+GSEvnmZ2ezTup1SBse9+twCCeial6EEi3Nc2KFcf6+qz2FBPnjXsk8xhKSaPQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"call-bind": "^1.0.2"
|
||||
}
|
||||
},
|
||||
"is-windows": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz",
|
||||
@@ -5071,6 +5112,15 @@
|
||||
"is-unicode-supported": "^0.1.0"
|
||||
}
|
||||
},
|
||||
"loupe": {
|
||||
"version": "2.3.4",
|
||||
"resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.4.tgz",
|
||||
"integrity": "sha512-OvKfgCC2Ndby6aSTREl5aCCPTNIzlDfQZvZxNUrBrihDhL3xcrYegTblhmEiCrg2kKQz4XsFIaemE5BF4ybSaQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"get-func-name": "^2.0.0"
|
||||
}
|
||||
},
|
||||
"lru-cache": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
|
||||
@@ -5322,33 +5372,32 @@
|
||||
"dev": true
|
||||
},
|
||||
"mocha": {
|
||||
"version": "9.1.1",
|
||||
"resolved": "https://registry.npmjs.org/mocha/-/mocha-9.1.1.tgz",
|
||||
"integrity": "sha512-0wE74YMgOkCgBUj8VyIDwmLUjTsS13WV1Pg7l0SHea2qzZzlq7MDnfbPsHKcELBRk3+izEVkRofjmClpycudCA==",
|
||||
"version": "9.2.0",
|
||||
"resolved": "https://registry.npmjs.org/mocha/-/mocha-9.2.0.tgz",
|
||||
"integrity": "sha512-kNn7E8g2SzVcq0a77dkphPsDSN7P+iYkqE0ZsGCYWRsoiKjOt+NvXfaagik8vuDa6W5Zw3qxe8Jfpt5qKf+6/Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@ungap/promise-all-settled": "1.1.2",
|
||||
"ansi-colors": "4.1.1",
|
||||
"browser-stdout": "1.3.1",
|
||||
"chokidar": "3.5.2",
|
||||
"debug": "4.3.1",
|
||||
"chokidar": "3.5.3",
|
||||
"debug": "4.3.3",
|
||||
"diff": "5.0.0",
|
||||
"escape-string-regexp": "4.0.0",
|
||||
"find-up": "5.0.0",
|
||||
"glob": "7.1.7",
|
||||
"glob": "7.2.0",
|
||||
"growl": "1.10.5",
|
||||
"he": "1.2.0",
|
||||
"js-yaml": "4.1.0",
|
||||
"log-symbols": "4.1.0",
|
||||
"minimatch": "3.0.4",
|
||||
"ms": "2.1.3",
|
||||
"nanoid": "3.1.23",
|
||||
"nanoid": "3.2.0",
|
||||
"serialize-javascript": "6.0.0",
|
||||
"strip-json-comments": "3.1.1",
|
||||
"supports-color": "8.1.1",
|
||||
"which": "2.0.2",
|
||||
"wide-align": "1.1.3",
|
||||
"workerpool": "6.1.5",
|
||||
"workerpool": "6.2.0",
|
||||
"yargs": "16.2.0",
|
||||
"yargs-parser": "20.2.4",
|
||||
"yargs-unparser": "2.0.0"
|
||||
@@ -5360,6 +5409,12 @@
|
||||
"integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==",
|
||||
"dev": true
|
||||
},
|
||||
"ansi-regex": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
|
||||
"dev": true
|
||||
},
|
||||
"anymatch": {
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz",
|
||||
@@ -5392,9 +5447,9 @@
|
||||
}
|
||||
},
|
||||
"chokidar": {
|
||||
"version": "3.5.2",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.2.tgz",
|
||||
"integrity": "sha512-ekGhOnNVPgT77r4K/U3GDhu+FQ2S8TnK/s2KbIGXi0SZWuwkZ2QNyfWdZW+TVfn84DpEP7rLeCt2UI6bJ8GwbQ==",
|
||||
"version": "3.5.3",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
|
||||
"integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"anymatch": "~3.1.2",
|
||||
@@ -5419,9 +5474,9 @@
|
||||
}
|
||||
},
|
||||
"debug": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
|
||||
"integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==",
|
||||
"version": "4.3.3",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz",
|
||||
"integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ms": "2.1.2"
|
||||
@@ -5567,14 +5622,25 @@
|
||||
}
|
||||
},
|
||||
"string-width": {
|
||||
"version": "4.2.2",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz",
|
||||
"integrity": "sha512-XBJbT3N4JhVumXE0eoLU9DCjcaF92KLNqTmFCnG1pf8duUxFGwtP6AD6nkjw9a3IdiRtL3E2w3JDiE/xi3vOeA==",
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
|
||||
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"emoji-regex": "^8.0.0",
|
||||
"is-fullwidth-code-point": "^3.0.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
"strip-ansi": "^6.0.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"strip-ansi": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
|
||||
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-regex": "^5.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"supports-color": {
|
||||
@@ -5683,22 +5749,23 @@
|
||||
}
|
||||
},
|
||||
"is-core-module": {
|
||||
"version": "2.6.0",
|
||||
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.6.0.tgz",
|
||||
"integrity": "sha512-wShG8vs60jKfPWpF2KZRaAtvt3a20OAn7+IJ6hLPECpSABLcKtFKTTI4ZtH5QcBruBHlq+WsdHWyz0BCZW7svQ==",
|
||||
"version": "2.8.1",
|
||||
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.8.1.tgz",
|
||||
"integrity": "sha512-SdNCUs284hr40hFTFP6l0IfZ/RSrMXF3qgoRHd3/79unUTvrFO/JoXwkGm+5J/Oe3E/b5GsnG330uUNgRpu1PA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"has": "^1.0.3"
|
||||
}
|
||||
},
|
||||
"resolve": {
|
||||
"version": "1.20.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.20.0.tgz",
|
||||
"integrity": "sha512-wENBPt4ySzg4ybFQW2TT1zMQucPK95HSh/nq2CFTZVOGut2+pQvSsgtda4d26YrYcr067wjbmzOG8byDPBX63A==",
|
||||
"version": "1.22.0",
|
||||
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.0.tgz",
|
||||
"integrity": "sha512-Hhtrw0nLeSrFQ7phPp4OOcVjLPIeMnRlr5mcnVuMe7M/7eBn98A3hmFRLoFo3DLZkivSYwhRUJTyPyWAk56WLw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"is-core-module": "^2.2.0",
|
||||
"path-parse": "^1.0.6"
|
||||
"is-core-module": "^2.8.1",
|
||||
"path-parse": "^1.0.7",
|
||||
"supports-preserve-symlinks-flag": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"through2": {
|
||||
@@ -5733,9 +5800,9 @@
|
||||
"optional": true
|
||||
},
|
||||
"nanoid": {
|
||||
"version": "3.1.23",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.23.tgz",
|
||||
"integrity": "sha512-FiB0kzdP0FFVGDKlRLEQ1BgDzU87dy5NnzjeW9YZNt+/c3+q82EQDUwniSAUxp/F0gFNI1ZhKU1FqYsMuqZVnw==",
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.2.0.tgz",
|
||||
"integrity": "sha512-fmsZYa9lpn69Ad5eDn7FMcnnSR+8R34W9qJEijxYhTbfOWzr22n1QxCMzXLK+ODyW2973V3Fux959iQoUxzUIA==",
|
||||
"dev": true
|
||||
},
|
||||
"nanomatch": {
|
||||
@@ -5770,10 +5837,13 @@
|
||||
"dev": true
|
||||
},
|
||||
"node-fetch": {
|
||||
"version": "2.6.1",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
|
||||
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==",
|
||||
"dev": true
|
||||
"version": "2.6.7",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
|
||||
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"whatwg-url": "^5.0.0"
|
||||
}
|
||||
},
|
||||
"normalize-package-data": {
|
||||
"version": "2.5.0",
|
||||
@@ -6173,6 +6243,12 @@
|
||||
"sha.js": "^2.4.8"
|
||||
}
|
||||
},
|
||||
"picocolors": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-0.2.1.tgz",
|
||||
"integrity": "sha512-cMlDqaLEqfSaW8Z7N5Jw+lyIW869EzT73/F5lhtY9cLGoVxSXznfgfXMO0Z5K0o0Q2TkTXq+0KFsdnSe3jDViA==",
|
||||
"dev": true
|
||||
},
|
||||
"picomatch": {
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz",
|
||||
@@ -6237,82 +6313,20 @@
|
||||
"dev": true
|
||||
},
|
||||
"postcss": {
|
||||
"version": "7.0.36",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-7.0.36.tgz",
|
||||
"integrity": "sha512-BebJSIUMwJHRH0HAQoxN4u1CN86glsrwsW0q7T+/m44eXOUAxSNdHRkNZPYz5vVUbg17hFgOQDE7fZk7li3pZw==",
|
||||
"version": "7.0.39",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-7.0.39.tgz",
|
||||
"integrity": "sha512-yioayjNbHn6z1/Bywyb2Y4s3yvDAeXGOyxqD+LnVOinq6Mdmd++SW2wUNVzavyyHxd6+DxzWGIuosg6P1Rj8uA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"chalk": "^2.4.2",
|
||||
"source-map": "^0.6.1",
|
||||
"supports-color": "^6.1.0"
|
||||
"picocolors": "^0.2.1",
|
||||
"source-map": "^0.6.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"ansi-styles": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
|
||||
"integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"color-convert": "^1.9.0"
|
||||
}
|
||||
},
|
||||
"chalk": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
|
||||
"integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-styles": "^3.2.1",
|
||||
"escape-string-regexp": "^1.0.5",
|
||||
"supports-color": "^5.3.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"supports-color": {
|
||||
"version": "5.5.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
|
||||
"integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"has-flag": "^3.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"color-convert": {
|
||||
"version": "1.9.3",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
|
||||
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"color-name": "1.1.3"
|
||||
}
|
||||
},
|
||||
"color-name": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
|
||||
"integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=",
|
||||
"dev": true
|
||||
},
|
||||
"has-flag": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz",
|
||||
"integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=",
|
||||
"dev": true
|
||||
},
|
||||
"source-map": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
||||
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
||||
"dev": true
|
||||
},
|
||||
"supports-color": {
|
||||
"version": "6.1.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz",
|
||||
"integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"has-flag": "^3.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -6806,9 +6820,9 @@
|
||||
}
|
||||
},
|
||||
"shell-quote": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.2.tgz",
|
||||
"integrity": "sha512-mRz/m/JVscCrkMyPqHc/bczi3OQHkLTqXHEFu0zDhK/qfv3UcOA4SVmRCLmos4bhjr9ekVQubj/R7waKapmiQg==",
|
||||
"version": "1.7.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.7.3.tgz",
|
||||
"integrity": "sha512-Vpfqwm4EnqGdlsBFNmHhxhElJYrdfcxPThu+ryKS5J8L/fhAwLazFZtq+S+TWZ9ANj2piSQLGj6NQg+lKPmxrw==",
|
||||
"dev": true
|
||||
},
|
||||
"side-channel": {
|
||||
@@ -7006,9 +7020,9 @@
|
||||
}
|
||||
},
|
||||
"source-map-support": {
|
||||
"version": "0.5.19",
|
||||
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.19.tgz",
|
||||
"integrity": "sha512-Wonm7zOCIJzBGQdB+thsPar0kYuCIzYvxZwlBa87yi/Mdjv7Tip2cyVbLj5o0cFPN4EVkuTwb3GDDyUx2DGnGw==",
|
||||
"version": "0.5.21",
|
||||
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
|
||||
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"buffer-from": "^1.0.0",
|
||||
@@ -7394,6 +7408,12 @@
|
||||
"has-flag": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"supports-preserve-symlinks-flag": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
|
||||
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
|
||||
"dev": true
|
||||
},
|
||||
"sver-compat": {
|
||||
"version": "1.5.0",
|
||||
"resolved": "https://registry.npmjs.org/sver-compat/-/sver-compat-1.5.0.tgz",
|
||||
@@ -7579,6 +7599,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"tr46": {
|
||||
"version": "0.0.3",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
|
||||
"integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=",
|
||||
"dev": true
|
||||
},
|
||||
"tsconfig-paths": {
|
||||
"version": "3.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.9.0.tgz",
|
||||
@@ -7654,9 +7680,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"typescript": {
|
||||
"version": "4.2.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.2.3.tgz",
|
||||
"integrity": "sha512-qOcYwxaByStAWrBf4x0fibwZvMRG+r4cQoTjbPtUlrWjBHbmCAww1i448U0GJ+3cNNEtebDteo/cHOR3xJ4wEw==",
|
||||
"version": "4.5.5",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.5.tgz",
|
||||
"integrity": "sha512-TCTIul70LyWe6IJWT8QSYeA54WQe8EjQFU4wY52Fasj5UKx88LNYKCgBEHcOMOrFF1rKGbD8v/xcNWVUq9SymA==",
|
||||
"dev": true
|
||||
},
|
||||
"umd": {
|
||||
@@ -8012,6 +8038,22 @@
|
||||
"integrity": "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ==",
|
||||
"dev": true
|
||||
},
|
||||
"webidl-conversions": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
|
||||
"integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=",
|
||||
"dev": true
|
||||
},
|
||||
"whatwg-url": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
|
||||
"integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"tr46": "~0.0.3",
|
||||
"webidl-conversions": "^3.0.0"
|
||||
}
|
||||
},
|
||||
"which": {
|
||||
"version": "1.3.1",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",
|
||||
@@ -8055,9 +8097,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"es-abstract": {
|
||||
"version": "1.18.6",
|
||||
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.18.6.tgz",
|
||||
"integrity": "sha512-kAeIT4cku5eNLNuUKhlmtuk1/TRZvQoYccn6TO0cSVdf1kzB0T7+dYuVK9MWM7l+/53W2Q8M7N2c6MQvhXFcUQ==",
|
||||
"version": "1.19.1",
|
||||
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.19.1.tgz",
|
||||
"integrity": "sha512-2vJ6tjA/UfqLm2MPs7jxVybLoB8i1t1Jd9R3kISld20sIxPcTbLuggQOUxeWeAvIUkduv/CfMjuh4WmiXr2v9w==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"call-bind": "^1.0.2",
|
||||
@@ -8071,7 +8113,9 @@
|
||||
"is-callable": "^1.2.4",
|
||||
"is-negative-zero": "^2.0.1",
|
||||
"is-regex": "^1.1.4",
|
||||
"is-shared-array-buffer": "^1.0.1",
|
||||
"is-string": "^1.0.7",
|
||||
"is-weakref": "^1.0.1",
|
||||
"object-inspect": "^1.11.0",
|
||||
"object-keys": "^1.1.1",
|
||||
"object.assign": "^4.1.2",
|
||||
@@ -8093,9 +8137,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"is-negative-zero": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.1.tgz",
|
||||
"integrity": "sha512-2z6JzQvZRa9A2Y7xC6dQQm4FSTSTNWjKIYYTt4246eMTJmIo0Q+ZyOsU66X8lxK1AbB92dFeglPLrhwpeRKO6w==",
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.2.tgz",
|
||||
"integrity": "sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==",
|
||||
"dev": true
|
||||
},
|
||||
"is-regex": {
|
||||
@@ -8118,9 +8162,9 @@
|
||||
}
|
||||
},
|
||||
"object-inspect": {
|
||||
"version": "1.11.0",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.11.0.tgz",
|
||||
"integrity": "sha512-jp7ikS6Sd3GxQfZJPyH3cjcbJF6GZPClgdV+EFygjFLQ5FmW/dRUnTd9PQ9k0JhoNDabWFbpF1yCdSWCC6gexg==",
|
||||
"version": "1.12.0",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.0.tgz",
|
||||
"integrity": "sha512-Ho2z80bVIvJloH+YzRmpZVQe87+qASmBUKZDWgx9cu+KDrX2ZDH/3tMy+gXbZETVGs2M8YdxObOh7XAtim9Y0g==",
|
||||
"dev": true
|
||||
},
|
||||
"object.assign": {
|
||||
@@ -8157,42 +8201,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"wide-align": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz",
|
||||
"integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"string-width": "^1.0.2 || 2"
|
||||
},
|
||||
"dependencies": {
|
||||
"ansi-regex": {
|
||||
"version": "3.0.0",
|
||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
|
||||
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
|
||||
"dev": true
|
||||
},
|
||||
"string-width": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
|
||||
"integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"is-fullwidth-code-point": "^2.0.0",
|
||||
"strip-ansi": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"strip-ansi": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
|
||||
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"ansi-regex": "^3.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"word-wrap": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz",
|
||||
@@ -8200,9 +8208,9 @@
|
||||
"dev": true
|
||||
},
|
||||
"workerpool": {
|
||||
"version": "6.1.5",
|
||||
"resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.5.tgz",
|
||||
"integrity": "sha512-XdKkCK0Zqc6w3iTxLckiuJ81tiD/o5rBE/m+nXpRCB+/Sq4DqkfXZ/x0jW02DG1tGsfUGXbTJyZDP+eu67haSw==",
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.0.tgz",
|
||||
"integrity": "sha512-Rsk5qQHJ9eowMH28Jwhe8HEbmdYDX4lwoMWshiCXugjtHqMD9ZbiqSDLxcsfdqsETPzVUtX5s1Z5kStiIM6l4A==",
|
||||
"dev": true
|
||||
},
|
||||
"wrap-ansi": {
|
||||
@@ -8466,9 +8474,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"camelcase": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.2.0.tgz",
|
||||
"integrity": "sha512-c7wVvbw3f37nuobQNtgsgG9POC9qMbNuMQmTCqZv23b6MIz0fcYpBiOlv9gEN/hdLdnZTDQhg6e9Dq5M1vKvfg==",
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
|
||||
"integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
|
||||
"dev": true
|
||||
},
|
||||
"decamelize": {
|
||||
|
||||
+5
-4
@@ -2,7 +2,7 @@
|
||||
"name": "typescript",
|
||||
"author": "Microsoft Corp.",
|
||||
"homepage": "https://www.typescriptlang.org/",
|
||||
"version": "4.5.0",
|
||||
"version": "4.7.0",
|
||||
"license": "Apache-2.0",
|
||||
"description": "TypeScript is a language for application scale JavaScript development",
|
||||
"keywords": [
|
||||
@@ -28,6 +28,7 @@
|
||||
"engines": {
|
||||
"node": ">=4.2.0"
|
||||
},
|
||||
"packageManager": "npm@6.14.15",
|
||||
"devDependencies": {
|
||||
"@octokit/rest": "latest",
|
||||
"@types/browserify": "latest",
|
||||
@@ -61,7 +62,7 @@
|
||||
"browser-resolve": "^1.11.2",
|
||||
"browserify": "latest",
|
||||
"chai": "latest",
|
||||
"chalk": "latest",
|
||||
"chalk": "^4.1.2",
|
||||
"convert-source-map": "latest",
|
||||
"del": "5.1.0",
|
||||
"diff": "^4.0.2",
|
||||
@@ -84,7 +85,7 @@
|
||||
"mkdirp": "latest",
|
||||
"mocha": "latest",
|
||||
"mocha-fivemat-progress-reporter": "latest",
|
||||
"ms": "latest",
|
||||
"ms": "^2.1.3",
|
||||
"node-fetch": "^2.6.1",
|
||||
"plugin-error": "latest",
|
||||
"pretty-hrtime": "^1.0.3",
|
||||
@@ -92,7 +93,7 @@
|
||||
"q": "latest",
|
||||
"source-map-support": "latest",
|
||||
"through2": "latest",
|
||||
"typescript": "^4.2.3",
|
||||
"typescript": "^4.5.5",
|
||||
"vinyl": "latest",
|
||||
"vinyl-sourcemaps-apply": "latest",
|
||||
"xml2js": "^0.4.19"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
const { join, resolve, dirname } = require("path");
|
||||
const { existsSync } = require("fs");
|
||||
|
||||
// search directories upward to avoid hard-wired paths based on the
|
||||
// build tree (same as src/harness/findUpDir.ts)
|
||||
|
||||
function findUpFile(name) {
|
||||
let dir = __dirname;
|
||||
while (true) {
|
||||
const fullPath = join(dir, name);
|
||||
if (existsSync(fullPath)) return fullPath;
|
||||
const up = resolve(dir, "..");
|
||||
if (up === dir) return name; // it'll fail anyway
|
||||
dir = up;
|
||||
}
|
||||
}
|
||||
exports.findUpFile = findUpFile;
|
||||
|
||||
const findUpRoot = () =>
|
||||
findUpRoot.cached || (findUpRoot.cached = dirname(findUpFile("Gulpfile.js")));
|
||||
exports.findUpRoot = findUpRoot;
|
||||
@@ -1,5 +1,7 @@
|
||||
// @ts-check
|
||||
const { exec, Debouncer } = require("./utils");
|
||||
const { resolve } = require("path");
|
||||
const { findUpRoot } = require("./findUpDir");
|
||||
|
||||
class ProjectQueue {
|
||||
/**
|
||||
@@ -33,7 +35,13 @@ class ProjectQueue {
|
||||
}
|
||||
}
|
||||
|
||||
const projectBuilder = new ProjectQueue((projects, lkg, force) => exec(process.execPath, [lkg ? "./lib/tsc" : "./built/local/tsc", "-b", ...(force ? ["--force"] : []), ...projects], { hidePrompt: true }));
|
||||
const execTsc = (lkg, ...args) =>
|
||||
exec(process.execPath,
|
||||
[resolve(findUpRoot(), lkg ? "./lib/tsc" : "./built/local/tsc"),
|
||||
"-b", ...args],
|
||||
{ hidePrompt: true });
|
||||
|
||||
const projectBuilder = new ProjectQueue((projects, lkg, force) => execTsc(lkg, ...(force ? ["--force"] : []), ...projects));
|
||||
|
||||
/**
|
||||
* @param {string} project
|
||||
@@ -43,14 +51,14 @@ const projectBuilder = new ProjectQueue((projects, lkg, force) => exec(process.e
|
||||
*/
|
||||
exports.buildProject = (project, { lkg, force } = {}) => projectBuilder.enqueue(project, { lkg, force });
|
||||
|
||||
const projectCleaner = new ProjectQueue((projects, lkg) => exec(process.execPath, [lkg ? "./lib/tsc" : "./built/local/tsc", "-b", "--clean", ...projects], { hidePrompt: true }));
|
||||
const projectCleaner = new ProjectQueue((projects, lkg) => execTsc(lkg, "--clean", ...projects));
|
||||
|
||||
/**
|
||||
* @param {string} project
|
||||
*/
|
||||
exports.cleanProject = (project) => projectCleaner.enqueue(project);
|
||||
|
||||
const projectWatcher = new ProjectQueue((projects) => exec(process.execPath, ["./lib/tsc", "-b", "--watch", ...projects], { hidePrompt: true }));
|
||||
const projectWatcher = new ProjectQueue((projects) => execTsc(true, "--watch", ...projects));
|
||||
|
||||
/**
|
||||
* @param {string} project
|
||||
|
||||
@@ -9,6 +9,7 @@ const log = require("fancy-log");
|
||||
const cmdLineOptions = require("./options");
|
||||
const { CancellationToken } = require("prex");
|
||||
const { exec } = require("./utils");
|
||||
const { findUpFile } = require("./findUpDir");
|
||||
|
||||
const mochaJs = require.resolve("mocha/bin/_mocha");
|
||||
exports.localBaseline = "tests/baselines/local/";
|
||||
@@ -73,11 +74,11 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode,
|
||||
/** @type {string[]} */
|
||||
let args = [];
|
||||
|
||||
// timeout normally isn"t necessary but Travis-CI has been timing out on compiler baselines occasionally
|
||||
// timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally
|
||||
// default timeout is 2sec which really should be enough, but maybe we just need a small amount longer
|
||||
if (!runInParallel) {
|
||||
args.push(mochaJs);
|
||||
args.push("-R", "scripts/failed-tests");
|
||||
args.push("-R", findUpFile("scripts/failed-tests.js"));
|
||||
args.push("-O", '"reporter=' + reporter + (keepFailed ? ",keepFailed=true" : "") + '"');
|
||||
if (tests) {
|
||||
args.push("-g", `"${tests}"`);
|
||||
|
||||
+4
-16
@@ -9,12 +9,11 @@ const del = require("del");
|
||||
const File = require("vinyl");
|
||||
const ts = require("../../lib/typescript");
|
||||
const chalk = require("chalk");
|
||||
const which = require("which");
|
||||
const { spawn } = require("child_process");
|
||||
const { CancellationToken, CancelError, Deferred } = require("prex");
|
||||
const { Readable, Duplex } = require("stream");
|
||||
|
||||
const isWindows = /^win/.test(process.platform);
|
||||
|
||||
/**
|
||||
* Executes the provided command once with the supplied arguments.
|
||||
* @param {string} cmd
|
||||
@@ -27,17 +26,13 @@ const isWindows = /^win/.test(process.platform);
|
||||
* @property {boolean} [hidePrompt]
|
||||
* @property {boolean} [waitForExit=true]
|
||||
*/
|
||||
function exec(cmd, args, options = {}) {
|
||||
async function exec(cmd, args, options = {}) {
|
||||
return /**@type {Promise<{exitCode: number}>}*/(new Promise((resolve, reject) => {
|
||||
const { ignoreExitCode, cancelToken = CancellationToken.none, waitForExit = true } = options;
|
||||
cancelToken.throwIfCancellationRequested();
|
||||
|
||||
// TODO (weswig): Update child_process types to add windowsVerbatimArguments to the type definition
|
||||
const subshellFlag = isWindows ? "/c" : "-c";
|
||||
const command = isWindows ? [possiblyQuote(cmd), ...args] : [`${cmd} ${args.join(" ")}`];
|
||||
|
||||
if (!options.hidePrompt) log(`> ${chalk.green(cmd)} ${args.join(" ")}`);
|
||||
const proc = spawn(isWindows ? "cmd" : "/bin/sh", [subshellFlag, ...command], { stdio: waitForExit ? "inherit" : "ignore", windowsVerbatimArguments: true });
|
||||
const proc = spawn(which.sync(cmd), args, { stdio: waitForExit ? "inherit" : "ignore" });
|
||||
const registration = cancelToken.register(() => {
|
||||
log(`${chalk.red("killing")} '${chalk.green(cmd)} ${args.join(" ")}'...`);
|
||||
proc.kill("SIGINT");
|
||||
@@ -68,13 +63,6 @@ function exec(cmd, args, options = {}) {
|
||||
}
|
||||
exports.exec = exec;
|
||||
|
||||
/**
|
||||
* @param {string} cmd
|
||||
*/
|
||||
function possiblyQuote(cmd) {
|
||||
return cmd.indexOf(" ") >= 0 ? `"${cmd}"` : cmd;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {ts.Diagnostic[]} diagnostics
|
||||
* @param {{ cwd?: string, pretty?: boolean }} [options]
|
||||
@@ -440,4 +428,4 @@ class Debouncer {
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.Debouncer = Debouncer;
|
||||
exports.Debouncer = Debouncer;
|
||||
|
||||
@@ -33,9 +33,9 @@ async function main() {
|
||||
|
||||
const inputPR = (await gh.pulls.get({ pull_number: +process.env.SOURCE_ISSUE, owner: "microsoft", repo: "TypeScript" })).data;
|
||||
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([
|
||||
["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url]]
|
||||
["git", ["remote", "add", "nonlocal", inputPR.base.repo.git_url.replace(/^git:(?:\/\/)?/, "https://")]]
|
||||
]);
|
||||
remoteName = "nonlocal";
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ function main(): void {
|
||||
const outputFilesDir = path.dirname(inputFilePath);
|
||||
const thisFilePathRel = path.relative(process.cwd(), outputFilesDir);
|
||||
|
||||
const infoFileOutput = buildInfoFileOutput(diagnosticMessages, "./diagnosticInformationMap.generated.ts", thisFilePathRel);
|
||||
const infoFileOutput = buildInfoFileOutput(diagnosticMessages, `./${path.basename(inputFilePath)}`, thisFilePathRel);
|
||||
checkForUniqueCodes(diagnosticMessages);
|
||||
writeFile("diagnosticInformationMap.generated.ts", infoFileOutput);
|
||||
|
||||
@@ -62,7 +62,7 @@ function checkForUniqueCodes(diagnosticTable: InputDiagnosticMessageTable) {
|
||||
function buildInfoFileOutput(messageTable: InputDiagnosticMessageTable, inputFilePathRel: string, thisFilePathRel: string): string {
|
||||
let result =
|
||||
"// <auto-generated />\r\n" +
|
||||
"// generated from '" + inputFilePathRel + "' by '" + thisFilePathRel.replace(/\\/g, "/") + "'\r\n" +
|
||||
"// generated from '" + inputFilePathRel + "' in '" + thisFilePathRel.replace(/\\/g, "/") + "'\r\n" +
|
||||
"/* @internal */\r\n" +
|
||||
"namespace ts {\r\n" +
|
||||
" function diag(code: number, category: DiagnosticCategory, key: string, message: string, reportsUnnecessary?: {}, elidedInCompatabilityPyramid?: boolean, reportsDeprecated?: {}): DiagnosticMessage {\r\n" +
|
||||
|
||||
+21
-20
@@ -174,14 +174,12 @@ namespace ts {
|
||||
const binder = createBinder();
|
||||
|
||||
export function bindSourceFile(file: SourceFile, options: CompilerOptions) {
|
||||
tracing?.push(tracing.Phase.Bind, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
|
||||
performance.mark("beforeBind");
|
||||
perfLogger.logStartBindFile("" + file.fileName);
|
||||
binder(file, options);
|
||||
perfLogger.logStopBindFile();
|
||||
performance.mark("afterBind");
|
||||
performance.measure("Bind", "beforeBind", "afterBind");
|
||||
tracing?.pop();
|
||||
}
|
||||
|
||||
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
|
||||
@@ -253,7 +251,9 @@ namespace ts {
|
||||
Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
|
||||
|
||||
if (!file.locals) {
|
||||
tracing?.push(tracing.Phase.Bind, "bindSourceFile", { path: file.path }, /*separateBeginAndEnd*/ true);
|
||||
bind(file);
|
||||
tracing?.pop();
|
||||
file.symbolCount = symbolCount;
|
||||
file.classifiableNames = classifiableNames;
|
||||
delayedBindJSDocTypedefTag();
|
||||
@@ -1365,7 +1365,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function maybeBindExpressionFlowIfCall(node: Expression) {
|
||||
// A top level or LHS of comma expression call expression with a dotted function name and at least one argument
|
||||
// A top level or comma expression call expression with a dotted function name and at least one argument
|
||||
// is potentially an assertion and is therefore included in the control flow.
|
||||
if (node.kind === SyntaxKind.CallExpression) {
|
||||
const call = node as CallExpression;
|
||||
@@ -1550,24 +1550,29 @@ namespace ts {
|
||||
return state;
|
||||
}
|
||||
|
||||
function onLeft(left: Expression, state: WorkArea, _node: BinaryExpression) {
|
||||
function onLeft(left: Expression, state: WorkArea, node: BinaryExpression) {
|
||||
if (!state.skip) {
|
||||
return maybeBind(left);
|
||||
const maybeBound = maybeBind(left);
|
||||
if (node.operatorToken.kind === SyntaxKind.CommaToken) {
|
||||
maybeBindExpressionFlowIfCall(left);
|
||||
}
|
||||
return maybeBound;
|
||||
}
|
||||
}
|
||||
|
||||
function onOperator(operatorToken: BinaryOperatorToken, state: WorkArea, node: BinaryExpression) {
|
||||
function onOperator(operatorToken: BinaryOperatorToken, state: WorkArea, _node: BinaryExpression) {
|
||||
if (!state.skip) {
|
||||
if (operatorToken.kind === SyntaxKind.CommaToken) {
|
||||
maybeBindExpressionFlowIfCall(node.left);
|
||||
}
|
||||
bind(operatorToken);
|
||||
}
|
||||
}
|
||||
|
||||
function onRight(right: Expression, state: WorkArea, _node: BinaryExpression) {
|
||||
function onRight(right: Expression, state: WorkArea, node: BinaryExpression) {
|
||||
if (!state.skip) {
|
||||
return maybeBind(right);
|
||||
const maybeBound = maybeBind(right);
|
||||
if (node.operatorToken.kind === SyntaxKind.CommaToken) {
|
||||
maybeBindExpressionFlowIfCall(right);
|
||||
}
|
||||
return maybeBound;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2066,12 +2071,6 @@ namespace ts {
|
||||
seen.set(identifier.escapedText, currentKind);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentKind === ElementKind.Property && existingKind === ElementKind.Property) {
|
||||
const span = getErrorSpanForNode(file, identifier);
|
||||
file.bindDiagnostics.push(createFileDiagnostic(file, span.start, span.length,
|
||||
Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2341,7 +2340,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function checkStrictModeNumericLiteral(node: NumericLiteral) {
|
||||
if (inStrictMode && node.numericLiteralFlags & TokenFlags.Octal) {
|
||||
if (languageVersion < ScriptTarget.ES5 && inStrictMode && node.numericLiteralFlags & TokenFlags.Octal) {
|
||||
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
|
||||
}
|
||||
}
|
||||
@@ -2374,7 +2373,7 @@ namespace ts {
|
||||
|
||||
function checkStrictModeLabeledStatement(node: LabeledStatement) {
|
||||
// Grammar checking for labeledStatement
|
||||
if (inStrictMode && options.target! >= ScriptTarget.ES2015) {
|
||||
if (inStrictMode && getEmitScriptTarget(options) >= ScriptTarget.ES2015) {
|
||||
if (isDeclarationStatement(node.statement) || isVariableStatement(node.statement)) {
|
||||
errorOnFirstToken(node.label, Diagnostics.A_label_is_not_allowed_here);
|
||||
}
|
||||
@@ -2409,6 +2408,7 @@ namespace ts {
|
||||
return;
|
||||
}
|
||||
setParent(node, parent);
|
||||
if (tracing) (node as TracingNode).tracingPath = file.path;
|
||||
const saveInStrictMode = inStrictMode;
|
||||
|
||||
// Even though in the AST the jsdoc @typedef node belongs to the current node,
|
||||
@@ -2947,6 +2947,7 @@ namespace ts {
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
case SyntaxKind.GetAccessor:
|
||||
case SyntaxKind.SetAccessor:
|
||||
case SyntaxKind.ClassStaticBlockDeclaration:
|
||||
// this.foo assignment in a JavaScript class
|
||||
// Bind this property to the containing class
|
||||
const containingClass = thisContainer.parent;
|
||||
@@ -3287,7 +3288,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (!isBindingPattern(node.name)) {
|
||||
if (isInJSFile(node) && isRequireVariableDeclaration(node) && !getJSDocTypeTag(node)) {
|
||||
if (isInJSFile(node) && isVariableDeclarationInitializedToBareOrAccessedRequire(node) && !getJSDocTypeTag(node)) {
|
||||
declareSymbolAndAddToSymbolTable(node as Declaration, SymbolFlags.Alias, SymbolFlags.AliasExcludes);
|
||||
}
|
||||
else if (isBlockOrCatchScoped(node)) {
|
||||
|
||||
+13
-5
@@ -258,6 +258,14 @@ namespace ts {
|
||||
Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
|
||||
state.seenAffectedFiles = state.seenAffectedFiles || new Set();
|
||||
}
|
||||
if (useOldState) {
|
||||
// Any time the interpretation of a source file changes, mark it as changed
|
||||
forEachEntry(oldState!.fileInfos, (info, sourceFilePath) => {
|
||||
if (state.fileInfos.has(sourceFilePath) && state.fileInfos.get(sourceFilePath)!.impliedFormat !== info.impliedFormat) {
|
||||
state.changedFilesSet.add(sourceFilePath);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
state.buildInfoEmitPending = !!state.changedFilesSet.size;
|
||||
return state;
|
||||
@@ -744,13 +752,13 @@ namespace ts {
|
||||
const actualSignature = signature ?? value.signature;
|
||||
return value.version === actualSignature ?
|
||||
value.affectsGlobalScope ?
|
||||
{ version: value.version, signature: undefined, affectsGlobalScope: true } :
|
||||
{ version: value.version, signature: undefined, affectsGlobalScope: true, impliedFormat: value.impliedFormat } :
|
||||
value.version :
|
||||
actualSignature !== undefined ?
|
||||
signature === undefined ?
|
||||
value :
|
||||
{ version: value.version, signature, affectsGlobalScope: value.affectsGlobalScope } :
|
||||
{ version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope };
|
||||
{ version: value.version, signature, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat } :
|
||||
{ version: value.version, signature: false, affectsGlobalScope: value.affectsGlobalScope, impliedFormat: value.impliedFormat };
|
||||
});
|
||||
|
||||
let referencedMap: ProgramBuildInfoReferencedMap | undefined;
|
||||
@@ -1243,10 +1251,10 @@ namespace ts {
|
||||
|
||||
export function toBuilderStateFileInfo(fileInfo: ProgramBuildInfoFileInfo): BuilderState.FileInfo {
|
||||
return isString(fileInfo) ?
|
||||
{ version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined } :
|
||||
{ version: fileInfo, signature: fileInfo, affectsGlobalScope: undefined, impliedFormat: undefined } :
|
||||
isString(fileInfo.signature) ?
|
||||
fileInfo as BuilderState.FileInfo :
|
||||
{ version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope };
|
||||
{ version: fileInfo.version, signature: fileInfo.signature === false ? undefined : fileInfo.version, affectsGlobalScope: fileInfo.affectsGlobalScope, impliedFormat: fileInfo.impliedFormat };
|
||||
}
|
||||
|
||||
export function createBuildProgramUsingProgramBuildInfo(program: ProgramBuildInfo, buildInfoPath: string, host: ReadBuildProgramHost): EmitAndSemanticDiagnosticsBuilderProgram {
|
||||
|
||||
@@ -82,6 +82,7 @@ namespace ts {
|
||||
readonly version: string;
|
||||
signature: string | undefined;
|
||||
affectsGlobalScope: boolean | undefined;
|
||||
impliedFormat: number | undefined;
|
||||
}
|
||||
|
||||
export interface ReadonlyManyToManyPathMap {
|
||||
@@ -332,7 +333,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
}
|
||||
fileInfos.set(sourceFile.resolvedPath, { version, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined });
|
||||
fileInfos.set(sourceFile.resolvedPath, { version, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) || undefined, impliedFormat: sourceFile.impliedNodeFormat });
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -433,7 +434,7 @@ namespace ts {
|
||||
);
|
||||
const firstDts = firstOrUndefined(emitOutput.outputFiles);
|
||||
if (firstDts) {
|
||||
Debug.assert(fileExtensionIs(firstDts.name, Extension.Dts), "File extension for signature expected to be dts", () => `Found: ${getAnyExtensionFromPath(firstDts.name)} for ${firstDts.name}:: All output files: ${JSON.stringify(emitOutput.outputFiles.map(f => f.name))}`);
|
||||
Debug.assert(fileExtensionIsOneOf(firstDts.name, [Extension.Dts, Extension.Dmts, Extension.Dcts]), "File extension for signature expected to be dts", () => `Found: ${getAnyExtensionFromPath(firstDts.name)} for ${firstDts.name}:: All output files: ${JSON.stringify(emitOutput.outputFiles.map(f => f.name))}`);
|
||||
latestSignature = (computeHash || generateDjb2Hash)(firstDts.text);
|
||||
if (exportedModulesMapCache && latestSignature !== prevSignature) {
|
||||
updateExportedModules(sourceFile, emitOutput.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
|
||||
|
||||
+2696
-1422
File diff suppressed because it is too large
Load Diff
+222
-122
@@ -1,6 +1,10 @@
|
||||
namespace ts {
|
||||
/* @internal */
|
||||
export const compileOnSaveCommandLineOption: CommandLineOption = { name: "compileOnSave", type: "boolean" };
|
||||
export const compileOnSaveCommandLineOption: CommandLineOption = {
|
||||
name: "compileOnSave",
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
};
|
||||
|
||||
const jsxOptionMap = new Map(getEntries({
|
||||
"preserve": JsxEmit.Preserve,
|
||||
@@ -29,6 +33,7 @@ namespace ts {
|
||||
["es2019", "lib.es2019.d.ts"],
|
||||
["es2020", "lib.es2020.d.ts"],
|
||||
["es2021", "lib.es2021.d.ts"],
|
||||
["es2022", "lib.es2022.d.ts"],
|
||||
["esnext", "lib.esnext.d.ts"],
|
||||
// Host only
|
||||
["dom", "lib.dom.d.ts"],
|
||||
@@ -72,12 +77,16 @@ namespace ts {
|
||||
["es2021.string", "lib.es2021.string.d.ts"],
|
||||
["es2021.weakref", "lib.es2021.weakref.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.asynciterable", "lib.es2018.asynciterable.d.ts"],
|
||||
["esnext.intl", "lib.esnext.intl.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.weakref", "lib.es2021.weakref.d.ts"]
|
||||
];
|
||||
@@ -112,6 +121,7 @@ namespace ts {
|
||||
})),
|
||||
category: Diagnostics.Watch_and_Build_Modes,
|
||||
description: Diagnostics.Specify_how_the_TypeScript_watch_mode_works,
|
||||
defaultValueDescription: WatchFileKind.UseFsEvents,
|
||||
},
|
||||
{
|
||||
name: "watchDirectory",
|
||||
@@ -123,6 +133,7 @@ namespace ts {
|
||||
})),
|
||||
category: Diagnostics.Watch_and_Build_Modes,
|
||||
description: Diagnostics.Specify_how_directories_are_watched_on_systems_that_lack_recursive_file_watching_functionality,
|
||||
defaultValueDescription: WatchDirectoryKind.UseFsEvents,
|
||||
},
|
||||
{
|
||||
name: "fallbackPolling",
|
||||
@@ -134,12 +145,14 @@ namespace ts {
|
||||
})),
|
||||
category: Diagnostics.Watch_and_Build_Modes,
|
||||
description: Diagnostics.Specify_what_approach_the_watcher_should_use_if_the_system_runs_out_of_native_file_watchers,
|
||||
defaultValueDescription: PollingWatchKind.PriorityInterval,
|
||||
},
|
||||
{
|
||||
name: "synchronousWatchDirectory",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Watch_and_Build_Modes,
|
||||
description: Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "excludeDirectories",
|
||||
@@ -176,11 +189,13 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Print_this_message,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "help",
|
||||
shortName: "?",
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "watch",
|
||||
@@ -190,6 +205,7 @@ namespace ts {
|
||||
isCommandLineOnly: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Watch_input_files,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "preserveWatchOutput",
|
||||
@@ -197,27 +213,28 @@ namespace ts {
|
||||
showInSimplifiedHelpView: false,
|
||||
category: Diagnostics.Output_Formatting,
|
||||
description: Diagnostics.Disable_wiping_the_console_in_watch_mode,
|
||||
defaultValueDescription: "n/a"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "listFiles",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Compiler_Diagnostics,
|
||||
description: Diagnostics.Print_all_of_the_files_read_during_the_compilation,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "explainFiles",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Compiler_Diagnostics,
|
||||
description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included
|
||||
description: Diagnostics.Print_files_read_during_the_compilation_including_why_it_was_included,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "listEmittedFiles",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Compiler_Diagnostics,
|
||||
description: Diagnostics.Print_the_names_of_emitted_files_after_a_compilation,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "pretty",
|
||||
@@ -225,28 +242,28 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Output_Formatting,
|
||||
description: Diagnostics.Enable_color_and_formatting_in_TypeScript_s_output_to_make_compiler_errors_easier_to_read,
|
||||
defaultValueDescription: "true"
|
||||
defaultValueDescription: true,
|
||||
},
|
||||
{
|
||||
name: "traceResolution",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Compiler_Diagnostics,
|
||||
description: Diagnostics.Log_paths_used_during_the_moduleResolution_process,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "diagnostics",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Compiler_Diagnostics,
|
||||
description: Diagnostics.Output_compiler_performance_information_after_building,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "extendedDiagnostics",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Compiler_Diagnostics,
|
||||
description: Diagnostics.Output_more_detailed_compiler_performance_information_after_building,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "generateCpuProfile",
|
||||
@@ -281,7 +298,8 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Watch_and_Build_Modes,
|
||||
description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
|
||||
description: Diagnostics.Have_recompiles_in_projects_that_use_incremental_and_watch_mode_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "locale",
|
||||
@@ -308,6 +326,7 @@ namespace ts {
|
||||
es2019: ScriptTarget.ES2019,
|
||||
es2020: ScriptTarget.ES2020,
|
||||
es2021: ScriptTarget.ES2021,
|
||||
es2022: ScriptTarget.ES2022,
|
||||
esnext: ScriptTarget.ESNext,
|
||||
})),
|
||||
affectsSourceFile: true,
|
||||
@@ -317,7 +336,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Language_and_Environment,
|
||||
description: Diagnostics.Set_the_JavaScript_language_version_for_emitted_JavaScript_and_include_compatible_library_declarations,
|
||||
defaultValueDescription: "ES3"
|
||||
defaultValueDescription: ScriptTarget.ES3,
|
||||
};
|
||||
|
||||
const commandOptionsWithoutBuild: CommandLineOption[] = [
|
||||
@@ -328,6 +347,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Show_all_compiler_options,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "version",
|
||||
@@ -336,6 +356,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Print_the_compiler_s_version,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "init",
|
||||
@@ -343,6 +364,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "project",
|
||||
@@ -360,7 +382,8 @@ namespace ts {
|
||||
shortName: "b",
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
|
||||
description: Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "showConfig",
|
||||
@@ -368,7 +391,8 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Command_line_Options,
|
||||
isCommandLineOnly: true,
|
||||
description: Diagnostics.Print_the_final_configuration_instead_of_building
|
||||
description: Diagnostics.Print_the_final_configuration_instead_of_building,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "listFilesOnly",
|
||||
@@ -377,7 +401,8 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
affectsEmit: true,
|
||||
isCommandLineOnly: true,
|
||||
description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
|
||||
description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
// Basic
|
||||
@@ -394,7 +419,10 @@ namespace ts {
|
||||
es6: ModuleKind.ES2015,
|
||||
es2015: ModuleKind.ES2015,
|
||||
es2020: ModuleKind.ES2020,
|
||||
esnext: ModuleKind.ESNext
|
||||
es2022: ModuleKind.ES2022,
|
||||
esnext: ModuleKind.ESNext,
|
||||
node12: ModuleKind.Node12,
|
||||
nodenext: ModuleKind.NodeNext,
|
||||
})),
|
||||
affectsModuleResolution: true,
|
||||
affectsEmit: true,
|
||||
@@ -402,13 +430,15 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Modules,
|
||||
description: Diagnostics.Specify_what_module_code_is_generated,
|
||||
defaultValueDescription: undefined,
|
||||
},
|
||||
{
|
||||
name: "lib",
|
||||
type: "list",
|
||||
element: {
|
||||
name: "lib",
|
||||
type: libMap
|
||||
type: libMap,
|
||||
defaultValueDescription: undefined,
|
||||
},
|
||||
affectsProgramStructure: true,
|
||||
showInSimplifiedHelpView: true,
|
||||
@@ -423,7 +453,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.JavaScript_Support,
|
||||
description: Diagnostics.Allow_JavaScript_files_to_be_a_part_of_your_program_Use_the_checkJS_option_to_get_errors_from_these_files,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "checkJs",
|
||||
@@ -431,7 +461,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.JavaScript_Support,
|
||||
description: Diagnostics.Enable_error_reporting_in_type_checked_JavaScript_files,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "jsx",
|
||||
@@ -443,7 +473,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Language_and_Environment,
|
||||
description: Diagnostics.Specify_what_JSX_code_is_generated,
|
||||
defaultValueDescription: "undefined"
|
||||
defaultValueDescription: undefined,
|
||||
},
|
||||
{
|
||||
name: "declaration",
|
||||
@@ -463,7 +493,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Emit,
|
||||
transpileOptionValue: undefined,
|
||||
defaultValueDescription: "false",
|
||||
defaultValueDescription: false,
|
||||
description: Diagnostics.Create_sourcemaps_for_d_ts_files
|
||||
},
|
||||
{
|
||||
@@ -475,7 +505,7 @@ namespace ts {
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Only_output_d_ts_files_and_not_JavaScript_files,
|
||||
transpileOptionValue: undefined,
|
||||
defaultValueDescription: "false",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "sourceMap",
|
||||
@@ -483,7 +513,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Emit,
|
||||
defaultValueDescription: "false",
|
||||
defaultValueDescription: false,
|
||||
description: Diagnostics.Create_source_map_files_for_emitted_JavaScript_files,
|
||||
},
|
||||
{
|
||||
@@ -496,7 +526,6 @@ namespace ts {
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Specify_a_file_that_bundles_all_outputs_into_one_JavaScript_file_If_declaration_is_true_also_designates_a_file_that_bundles_all_d_ts_output,
|
||||
transpileOptionValue: undefined,
|
||||
defaultValueDescription: "n/a"
|
||||
},
|
||||
{
|
||||
name: "outDir",
|
||||
@@ -507,7 +536,6 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Specify_an_output_folder_for_all_emitted_files,
|
||||
defaultValueDescription: "n/a"
|
||||
},
|
||||
{
|
||||
name: "rootDir",
|
||||
@@ -526,7 +554,7 @@ namespace ts {
|
||||
isTSConfigOnly: true,
|
||||
category: Diagnostics.Projects,
|
||||
transpileOptionValue: undefined,
|
||||
defaultValueDescription: "false",
|
||||
defaultValueDescription: false,
|
||||
description: Diagnostics.Enable_constraints_that_allow_a_TypeScript_project_to_be_used_with_project_references,
|
||||
},
|
||||
{
|
||||
@@ -546,7 +574,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Emit,
|
||||
defaultValueDescription: "false",
|
||||
defaultValueDescription: false,
|
||||
description: Diagnostics.Disable_emitting_comments,
|
||||
},
|
||||
{
|
||||
@@ -556,7 +584,7 @@ namespace ts {
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Disable_emitting_files_from_a_compilation,
|
||||
transpileOptionValue: undefined,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "importHelpers",
|
||||
@@ -564,7 +592,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Allow_importing_helper_functions_from_tslib_once_per_project_instead_of_including_them_per_file,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "importsNotUsedAsValues",
|
||||
@@ -576,7 +604,8 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
|
||||
description: Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types,
|
||||
defaultValueDescription: ImportsNotUsedAsValues.Remove,
|
||||
},
|
||||
{
|
||||
name: "downlevelIteration",
|
||||
@@ -584,7 +613,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Emit_more_compliant_but_verbose_and_less_performant_JavaScript_for_iteration,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "isolatedModules",
|
||||
@@ -592,7 +621,7 @@ namespace ts {
|
||||
category: Diagnostics.Interop_Constraints,
|
||||
description: Diagnostics.Ensure_that_each_file_can_be_safely_transpiled_without_relying_on_other_imports,
|
||||
transpileOptionValue: true,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
// Strict Type Checks
|
||||
@@ -604,7 +633,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Enable_all_strict_type_checking_options,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noImplicitAny",
|
||||
@@ -665,6 +694,7 @@ namespace ts {
|
||||
strictFlag: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Type_catch_clause_variables_as_unknown_instead_of_any,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "alwaysStrict",
|
||||
@@ -683,7 +713,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Enable_error_reporting_when_a_local_variables_aren_t_read,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noUnusedParameters",
|
||||
@@ -691,14 +721,15 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Raise_an_error_when_a_function_parameter_isn_t_read,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "exactOptionalPropertyTypes",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined
|
||||
description: Diagnostics.Interpret_optional_property_types_as_written_rather_than_adding_undefined,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noImplicitReturns",
|
||||
@@ -706,7 +737,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Enable_error_reporting_for_codepaths_that_do_not_explicitly_return_in_a_function,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noFallthroughCasesInSwitch",
|
||||
@@ -714,21 +745,24 @@ namespace ts {
|
||||
affectsBindDiagnostics: true,
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements
|
||||
description: Diagnostics.Enable_error_reporting_for_fallthrough_cases_in_switch_statements,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noUncheckedIndexedAccess",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Include_undefined_in_index_signature_results
|
||||
description: Diagnostics.Include_undefined_in_index_signature_results,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noImplicitOverride",
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier
|
||||
description: Diagnostics.Ensure_overriding_members_in_derived_classes_are_marked_with_an_override_modifier,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noPropertyAccessFromIndexSignature",
|
||||
@@ -736,7 +770,7 @@ namespace ts {
|
||||
showInSimplifiedHelpView: false,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Enforces_using_indexed_accessors_for_keys_declared_using_an_indexed_type,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
// Module Resolution
|
||||
@@ -745,6 +779,8 @@ namespace ts {
|
||||
type: new Map(getEntries({
|
||||
node: ModuleResolutionKind.NodeJs,
|
||||
classic: ModuleResolutionKind.Classic,
|
||||
node12: ModuleResolutionKind.Node12,
|
||||
nodenext: ModuleResolutionKind.NodeNext,
|
||||
})),
|
||||
affectsModuleResolution: true,
|
||||
paramType: Diagnostics.STRATEGY,
|
||||
@@ -829,14 +865,14 @@ namespace ts {
|
||||
showInSimplifiedHelpView: true,
|
||||
category: Diagnostics.Interop_Constraints,
|
||||
description: Diagnostics.Emit_additional_JavaScript_to_ease_support_for_importing_CommonJS_modules_This_enables_allowSyntheticDefaultImports_for_type_compatibility,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "preserveSymlinks",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Interop_Constraints,
|
||||
description: Diagnostics.Disable_resolving_symlinks_to_their_realpath_This_correlates_to_the_same_flag_in_node,
|
||||
defaultValueDescription: "n/a"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "allowUmdGlobalAccess",
|
||||
@@ -844,7 +880,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Modules,
|
||||
description: Diagnostics.Allow_accessing_UMD_globals_from_modules,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
// Source Maps
|
||||
@@ -870,7 +906,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Include_sourcemap_files_inside_the_emitted_JavaScript,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "inlineSources",
|
||||
@@ -878,7 +914,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Include_source_code_in_the_sourcemaps_inside_the_emitted_JavaScript,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
// Experimental
|
||||
@@ -887,7 +923,8 @@ namespace ts {
|
||||
type: "boolean",
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Language_and_Environment,
|
||||
description: Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators
|
||||
description: Diagnostics.Enable_experimental_support_for_TC39_stage_2_draft_decorators,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "emitDecoratorMetadata",
|
||||
@@ -895,7 +932,8 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Language_and_Environment,
|
||||
description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files
|
||||
description: Diagnostics.Emit_design_type_metadata_for_decorated_declarations_in_source_files,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
// Advanced
|
||||
@@ -928,7 +966,7 @@ namespace ts {
|
||||
affectsModuleResolution: true,
|
||||
category: Diagnostics.Modules,
|
||||
description: Diagnostics.Enable_importing_json_files,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
{
|
||||
@@ -940,7 +978,6 @@ namespace ts {
|
||||
category: Diagnostics.Backwards_Compatibility,
|
||||
paramType: Diagnostics.FILE,
|
||||
transpileOptionValue: undefined,
|
||||
defaultValueDescription: "n/a",
|
||||
description: Diagnostics.Deprecated_setting_Use_outFile_instead,
|
||||
},
|
||||
{
|
||||
@@ -956,7 +993,7 @@ namespace ts {
|
||||
type: "boolean",
|
||||
category: Diagnostics.Completeness,
|
||||
description: Diagnostics.Skip_type_checking_d_ts_files_that_are_included_with_TypeScript,
|
||||
defaultValueDescription: "false",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "charset",
|
||||
@@ -971,7 +1008,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "newLine",
|
||||
@@ -991,7 +1028,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Output_Formatting,
|
||||
description: Diagnostics.Disable_truncating_types_in_error_messages,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noLib",
|
||||
@@ -1002,7 +1039,7 @@ namespace ts {
|
||||
// We are not returning a sourceFile for lib file when asked by the program,
|
||||
// so pass --noLib to avoid reporting a file not found error.
|
||||
transpileOptionValue: true,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noResolve",
|
||||
@@ -1013,7 +1050,7 @@ namespace ts {
|
||||
// We are not doing a full typecheck, we are not resolving the whole context,
|
||||
// so pass --noResolve to avoid reporting missing file errors.
|
||||
transpileOptionValue: true,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "stripInternal",
|
||||
@@ -1021,6 +1058,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Disable_emitting_declarations_that_have_internal_in_their_JSDoc_comments,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "disableSizeLimit",
|
||||
@@ -1028,28 +1066,31 @@ namespace ts {
|
||||
affectsProgramStructure: true,
|
||||
category: Diagnostics.Editor_Support,
|
||||
description: Diagnostics.Remove_the_20mb_cap_on_total_source_code_size_for_JavaScript_files_in_the_TypeScript_language_server,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "disableSourceOfProjectReferenceRedirect",
|
||||
type: "boolean",
|
||||
isTSConfigOnly: true,
|
||||
category: Diagnostics.Projects,
|
||||
description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects
|
||||
description: Diagnostics.Disable_preferring_source_files_instead_of_declaration_files_when_referencing_composite_projects,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "disableSolutionSearching",
|
||||
type: "boolean",
|
||||
isTSConfigOnly: true,
|
||||
category: Diagnostics.Projects,
|
||||
description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing
|
||||
description: Diagnostics.Opt_a_project_out_of_multi_project_reference_checking_when_editing,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "disableReferencedProjectLoad",
|
||||
type: "boolean",
|
||||
isTSConfigOnly: true,
|
||||
category: Diagnostics.Projects,
|
||||
description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript
|
||||
description: Diagnostics.Reduce_the_number_of_projects_loaded_automatically_by_TypeScript,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noImplicitUseStrict",
|
||||
@@ -1057,7 +1098,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Backwards_Compatibility,
|
||||
description: Diagnostics.Disable_adding_use_strict_directives_in_emitted_JavaScript_files,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noEmitHelpers",
|
||||
@@ -1065,7 +1106,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Disable_generating_custom_helper_functions_like_extends_in_compiled_output,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "noEmitOnError",
|
||||
@@ -1074,7 +1115,7 @@ namespace ts {
|
||||
category: Diagnostics.Emit,
|
||||
transpileOptionValue: undefined,
|
||||
description: Diagnostics.Disable_emitting_files_if_any_type_checking_errors_are_reported,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "preserveConstEnums",
|
||||
@@ -1082,7 +1123,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Disable_erasing_const_enum_declarations_in_generated_code,
|
||||
defaultValueDescription: "n/a"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "declarationDir",
|
||||
@@ -1093,14 +1134,13 @@ namespace ts {
|
||||
category: Diagnostics.Emit,
|
||||
transpileOptionValue: undefined,
|
||||
description: Diagnostics.Specify_the_output_directory_for_generated_declaration_files,
|
||||
defaultValueDescription: "n/a"
|
||||
},
|
||||
{
|
||||
name: "skipLibCheck",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Completeness,
|
||||
description: Diagnostics.Skip_type_checking_all_d_ts_files,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "allowUnusedLabels",
|
||||
@@ -1109,7 +1149,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Disable_error_reporting_for_unused_labels,
|
||||
defaultValueDescription: "undefined"
|
||||
defaultValueDescription: undefined,
|
||||
},
|
||||
{
|
||||
name: "allowUnreachableCode",
|
||||
@@ -1118,7 +1158,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Type_Checking,
|
||||
description: Diagnostics.Disable_error_reporting_for_unreachable_code,
|
||||
defaultValueDescription: "undefined"
|
||||
defaultValueDescription: undefined,
|
||||
},
|
||||
{
|
||||
name: "suppressExcessPropertyErrors",
|
||||
@@ -1126,7 +1166,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Backwards_Compatibility,
|
||||
description: Diagnostics.Disable_reporting_of_excess_property_errors_during_the_creation_of_object_literals,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "suppressImplicitAnyIndexErrors",
|
||||
@@ -1134,7 +1174,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Backwards_Compatibility,
|
||||
description: Diagnostics.Suppress_noImplicitAny_errors_when_indexing_objects_that_lack_index_signatures,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "forceConsistentCasingInFileNames",
|
||||
@@ -1142,7 +1182,7 @@ namespace ts {
|
||||
affectsModuleResolution: true,
|
||||
category: Diagnostics.Interop_Constraints,
|
||||
description: Diagnostics.Ensure_that_casing_is_correct_in_imports,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "maxNodeModuleJsDepth",
|
||||
@@ -1150,7 +1190,7 @@ namespace ts {
|
||||
affectsModuleResolution: true,
|
||||
category: Diagnostics.JavaScript_Support,
|
||||
description: Diagnostics.Specify_the_maximum_folder_depth_used_for_checking_JavaScript_files_from_node_modules_Only_applicable_with_allowJs,
|
||||
defaultValueDescription: "0"
|
||||
defaultValueDescription: 0,
|
||||
},
|
||||
{
|
||||
name: "noStrictGenericChecks",
|
||||
@@ -1158,7 +1198,7 @@ namespace ts {
|
||||
affectsSemanticDiagnostics: true,
|
||||
category: Diagnostics.Backwards_Compatibility,
|
||||
description: Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "useDefineForClassFields",
|
||||
@@ -1175,6 +1215,7 @@ namespace ts {
|
||||
affectsEmit: true,
|
||||
category: Diagnostics.Emit,
|
||||
description: Diagnostics.Preserve_unused_imported_values_in_the_JavaScript_output_that_would_otherwise_be_removed,
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
|
||||
{
|
||||
@@ -1182,7 +1223,7 @@ namespace ts {
|
||||
type: "boolean",
|
||||
category: Diagnostics.Backwards_Compatibility,
|
||||
description: Diagnostics.Make_keyof_only_return_strings_instead_of_string_numbers_or_symbols_Legacy_option,
|
||||
defaultValueDescription: "false"
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
// A list of plugins to load in the language service
|
||||
@@ -1237,27 +1278,31 @@ namespace ts {
|
||||
shortName: "v",
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Enable_verbose_logging,
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "dry",
|
||||
shortName: "d",
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "force",
|
||||
shortName: "f",
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "clean",
|
||||
category: Diagnostics.Command_line_Options,
|
||||
description: Diagnostics.Delete_the_outputs_of_all_projects,
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
}
|
||||
];
|
||||
|
||||
@@ -1275,10 +1320,12 @@ namespace ts {
|
||||
*/
|
||||
name: "enableAutoDiscovery",
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "enable",
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
{
|
||||
name: "include",
|
||||
@@ -1299,6 +1346,7 @@ namespace ts {
|
||||
{
|
||||
name: "disableFilenameBasedTypeAcquisition",
|
||||
type: "boolean",
|
||||
defaultValueDescription: false,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1337,7 +1385,7 @@ namespace ts {
|
||||
/* @internal */
|
||||
export const defaultInitCompilerOptions: CompilerOptions = {
|
||||
module: ModuleKind.CommonJS,
|
||||
target: ScriptTarget.ES5,
|
||||
target: ScriptTarget.ES2016,
|
||||
strict: true,
|
||||
esModuleInterop: true,
|
||||
forceConsistentCasingInFileNames: true,
|
||||
@@ -2280,7 +2328,7 @@ namespace ts {
|
||||
return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
|
||||
}
|
||||
else {
|
||||
return (optionDefinition as CommandLineOptionOfCustomType).type;
|
||||
return optionDefinition.type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2348,6 +2396,47 @@ namespace ts {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a list of the compiler options whose value is not the default.
|
||||
* @param options compilerOptions to be evaluated.
|
||||
/** @internal */
|
||||
export function getCompilerOptionsDiffValue(options: CompilerOptions, newLine: string): string {
|
||||
const compilerOptionsMap = getSerializedCompilerOption(options);
|
||||
return getOverwrittenDefaultOptions();
|
||||
|
||||
function makePadding(paddingLength: number): string {
|
||||
return Array(paddingLength + 1).join(" ");
|
||||
}
|
||||
|
||||
function getOverwrittenDefaultOptions() {
|
||||
const result: string[] = [];
|
||||
const tab = makePadding(2);
|
||||
commandOptionsWithoutBuild.forEach(cmd => {
|
||||
if (!compilerOptionsMap.has(cmd.name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newValue = compilerOptionsMap.get(cmd.name);
|
||||
const defaultValue = getDefaultValueForOption(cmd);
|
||||
if (newValue !== defaultValue) {
|
||||
result.push(`${tab}${cmd.name}: ${newValue}`);
|
||||
}
|
||||
else if (hasProperty(defaultInitCompilerOptions, cmd.name)) {
|
||||
result.push(`${tab}${cmd.name}: ${defaultValue}`);
|
||||
}
|
||||
});
|
||||
return result.join(newLine) + newLine;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the compiler options to be written into the tsconfig.json.
|
||||
* @param options commandlineOptions to be included in the compileOptions.
|
||||
*/
|
||||
function getSerializedCompilerOption(options: CompilerOptions): ESMap<string, CompilerOptionsValue> {
|
||||
const compilerOptions = extend(options, defaultInitCompilerOptions);
|
||||
return serializeCompilerOptions(compilerOptions);
|
||||
}
|
||||
/**
|
||||
* Generate tsconfig configuration when running command line "--init"
|
||||
* @param options commandlineOptions to be generated into tsconfig.json
|
||||
@@ -2355,29 +2444,9 @@ namespace ts {
|
||||
*/
|
||||
/* @internal */
|
||||
export function generateTSConfig(options: CompilerOptions, fileNames: readonly string[], newLine: string): string {
|
||||
const compilerOptions = extend(options, defaultInitCompilerOptions);
|
||||
const compilerOptionsMap = serializeCompilerOptions(compilerOptions);
|
||||
const compilerOptionsMap = getSerializedCompilerOption(options);
|
||||
return writeConfigurations();
|
||||
|
||||
function getDefaultValueForOption(option: CommandLineOption) {
|
||||
switch (option.type) {
|
||||
case "number":
|
||||
return 1;
|
||||
case "boolean":
|
||||
return true;
|
||||
case "string":
|
||||
return option.isFilePath ? "./" : "";
|
||||
case "list":
|
||||
return [];
|
||||
case "object":
|
||||
return {};
|
||||
default:
|
||||
const iterResult = option.type.keys().next();
|
||||
if (!iterResult.done) return iterResult.value;
|
||||
return Debug.fail("Expected 'option.type' to have entries.");
|
||||
}
|
||||
}
|
||||
|
||||
function makePadding(paddingLength: number): string {
|
||||
return Array(paddingLength + 1).join(" ");
|
||||
}
|
||||
@@ -3087,7 +3156,7 @@ namespace ts {
|
||||
if (isCompilerOptionsValue(opt, value)) {
|
||||
const optType = opt.type;
|
||||
if (optType === "list" && isArray(value)) {
|
||||
return convertJsonOptionOfListType(opt as CommandLineOptionOfListType, value, basePath, errors);
|
||||
return convertJsonOptionOfListType(opt , value, basePath, errors);
|
||||
}
|
||||
else if (!isString(optType)) {
|
||||
return convertJsonOptionOfCustomType(opt as CommandLineOptionOfCustomType, value as string, errors);
|
||||
@@ -3216,7 +3285,7 @@ namespace ts {
|
||||
// Rather than re-query this for each file and filespec, we query the supported extensions
|
||||
// once and store it on the expansion context.
|
||||
const supportedExtensions = getSupportedExtensions(options, extraFileExtensions);
|
||||
const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
|
||||
const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
|
||||
|
||||
// Literal files are always included verbatim. An "include" or "exclude" specification cannot
|
||||
// remove a literal file.
|
||||
@@ -3229,7 +3298,7 @@ namespace ts {
|
||||
|
||||
let jsonOnlyIncludeRegexes: readonly RegExp[] | undefined;
|
||||
if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
|
||||
for (const file of host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) {
|
||||
for (const file of host.readDirectory(basePath, flatten(supportedExtensionsWithJsonIfResolveJsonModule), validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined)) {
|
||||
if (fileExtensionIs(file, Extension.Json)) {
|
||||
// Valid only if *.json specified
|
||||
if (!jsonOnlyIncludeRegexes) {
|
||||
@@ -3440,7 +3509,7 @@ namespace ts {
|
||||
? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None
|
||||
};
|
||||
}
|
||||
if (isImplicitGlob(spec)) {
|
||||
if (isImplicitGlob(spec.substring(spec.lastIndexOf(directorySeparator) + 1))) {
|
||||
return {
|
||||
key: useCaseSensitiveFileNames ? spec : toFileNameLowerCase(spec),
|
||||
flags: WatchDirectoryFlags.Recursive
|
||||
@@ -3454,16 +3523,24 @@ namespace ts {
|
||||
* extension priority.
|
||||
*
|
||||
* @param file The path to the file.
|
||||
* @param extensionPriority The priority of the extension.
|
||||
* @param context The expansion context.
|
||||
*/
|
||||
function hasFileWithHigherPriorityExtension(file: string, literalFiles: ESMap<string, string>, wildcardFiles: ESMap<string, string>, extensions: readonly string[], keyMapper: (value: string) => string) {
|
||||
const extensionPriority = getExtensionPriority(file, extensions);
|
||||
const adjustedExtensionPriority = adjustExtensionPriority(extensionPriority, extensions);
|
||||
for (let i = ExtensionPriority.Highest; i < adjustedExtensionPriority; i++) {
|
||||
const higherPriorityExtension = extensions[i];
|
||||
const higherPriorityPath = keyMapper(changeExtension(file, higherPriorityExtension));
|
||||
function hasFileWithHigherPriorityExtension(file: string, literalFiles: ESMap<string, string>, wildcardFiles: ESMap<string, string>, extensions: readonly string[][], keyMapper: (value: string) => string) {
|
||||
const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined);
|
||||
if (!extensionGroup) {
|
||||
return false;
|
||||
}
|
||||
for (const ext of extensionGroup) {
|
||||
if (fileExtensionIs(file, ext)) {
|
||||
return false;
|
||||
}
|
||||
const higherPriorityPath = keyMapper(changeExtension(file, ext));
|
||||
if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
|
||||
if (ext === Extension.Dts && (fileExtensionIs(file, Extension.Js) || fileExtensionIs(file, Extension.Jsx))) {
|
||||
// LEGACY BEHAVIOR: An off-by-one bug somewhere in the extension priority system for wildcard module loading allowed declaration
|
||||
// files to be loaded alongside their js(x) counterparts. We regard this as generally undesirable, but retain the behavior to
|
||||
// prevent breakage.
|
||||
continue;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -3476,15 +3553,18 @@ namespace ts {
|
||||
* already been included.
|
||||
*
|
||||
* @param file The path to the file.
|
||||
* @param extensionPriority The priority of the extension.
|
||||
* @param context The expansion context.
|
||||
*/
|
||||
function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: ESMap<string, string>, extensions: readonly string[], keyMapper: (value: string) => string) {
|
||||
const extensionPriority = getExtensionPriority(file, extensions);
|
||||
const nextExtensionPriority = getNextLowestExtensionPriority(extensionPriority, extensions);
|
||||
for (let i = nextExtensionPriority; i < extensions.length; i++) {
|
||||
const lowerPriorityExtension = extensions[i];
|
||||
const lowerPriorityPath = keyMapper(changeExtension(file, lowerPriorityExtension));
|
||||
function removeWildcardFilesWithLowerPriorityExtension(file: string, wildcardFiles: ESMap<string, string>, extensions: readonly string[][], keyMapper: (value: string) => string) {
|
||||
const extensionGroup = forEach(extensions, group => fileExtensionIsOneOf(file, group) ? group : undefined);
|
||||
if (!extensionGroup) {
|
||||
return;
|
||||
}
|
||||
for (let i = extensionGroup.length - 1; i >= 0; i--) {
|
||||
const ext = extensionGroup[i];
|
||||
if (fileExtensionIs(file, ext)) {
|
||||
return;
|
||||
}
|
||||
const lowerPriorityPath = keyMapper(changeExtension(file, ext));
|
||||
wildcardFiles.delete(lowerPriorityPath);
|
||||
}
|
||||
}
|
||||
@@ -3528,4 +3608,24 @@ namespace ts {
|
||||
})!; // TODO: GH#18217
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function getDefaultValueForOption(option: CommandLineOption) {
|
||||
switch (option.type) {
|
||||
case "number":
|
||||
return 1;
|
||||
case "boolean":
|
||||
return true;
|
||||
case "string":
|
||||
return option.isFilePath ? "./" : "";
|
||||
case "list":
|
||||
return [];
|
||||
case "object":
|
||||
return {};
|
||||
default:
|
||||
const iterResult = option.type.keys().next();
|
||||
if (!iterResult.done) return iterResult.value;
|
||||
return Debug.fail("Expected 'option.type' to have entries.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
-53
@@ -1,25 +1,5 @@
|
||||
/* @internal */
|
||||
namespace ts {
|
||||
type GetIteratorCallback = <I extends readonly any[] | ReadonlySet<any> | ReadonlyESMap<any, any> | undefined>(iterable: I) => Iterator<
|
||||
I extends ReadonlyESMap<infer K, infer V> ? [K, V] :
|
||||
I extends ReadonlySet<infer T> ? T :
|
||||
I extends readonly (infer T)[] ? T :
|
||||
I extends undefined ? undefined :
|
||||
never>;
|
||||
|
||||
function getCollectionImplementation<
|
||||
K1 extends MatchingKeys<typeof NativeCollections, () => any>,
|
||||
K2 extends MatchingKeys<typeof ShimCollections, (getIterator?: GetIteratorCallback) => ReturnType<(typeof NativeCollections)[K1]>>
|
||||
>(name: string, nativeFactory: K1, shimFactory: K2): NonNullable<ReturnType<(typeof NativeCollections)[K1]>> {
|
||||
// NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
|
||||
const constructor = NativeCollections[nativeFactory]() ?? ShimCollections?.[shimFactory](getIterator);
|
||||
if (constructor) return constructor as NonNullable<ReturnType<(typeof NativeCollections)[K1]>>;
|
||||
throw new Error(`TypeScript requires an environment that provides a compatible native ${name} implementation.`);
|
||||
}
|
||||
|
||||
export const Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
|
||||
export const Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
|
||||
|
||||
export function getIterator<I extends readonly any[] | ReadonlySet<any> | ReadonlyESMap<any, any> | undefined>(iterable: I): Iterator<
|
||||
I extends ReadonlyESMap<infer K, infer V> ? [K, V] :
|
||||
I extends ReadonlySet<infer T> ? T :
|
||||
@@ -43,34 +23,6 @@ namespace ts {
|
||||
export const emptyMap: ReadonlyESMap<never, never> = new Map<never, 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 {
|
||||
return array ? array.length : 0;
|
||||
}
|
||||
@@ -818,7 +770,11 @@ namespace ts {
|
||||
return deduplicated as any as SortedReadonlyArray<T>;
|
||||
}
|
||||
|
||||
export function insertSorted<T>(array: SortedArray<T>, insert: T, compare: Comparer<T>): void {
|
||||
export function createSortedArray<T>(): SortedArray<T> {
|
||||
return [] as any as SortedArray<T>; // TODO: GH#19873
|
||||
}
|
||||
|
||||
export function insertSorted<T>(array: SortedArray<T>, insert: T, compare: Comparer<T>, allowDuplicates?: boolean): void {
|
||||
if (array.length === 0) {
|
||||
array.push(insert);
|
||||
return;
|
||||
@@ -828,6 +784,9 @@ namespace ts {
|
||||
if (insertIndex < 0) {
|
||||
array.splice(~insertIndex, 0, insert);
|
||||
}
|
||||
else if (allowDuplicates) {
|
||||
array.splice(insertIndex, 0, insert);
|
||||
}
|
||||
}
|
||||
|
||||
export function sortAndDeduplicate<T>(array: readonly string[]): SortedReadonlyArray<string>;
|
||||
@@ -1293,11 +1252,11 @@ namespace ts {
|
||||
return result;
|
||||
}
|
||||
|
||||
export function getOwnValues<T>(sparseArray: T[]): T[] {
|
||||
export function getOwnValues<T>(collection: MapLike<T> | T[]): T[] {
|
||||
const values: T[] = [];
|
||||
for (const key in sparseArray) {
|
||||
if (hasOwnProperty.call(sparseArray, key)) {
|
||||
values.push(sparseArray[key]);
|
||||
for (const key in collection) {
|
||||
if (hasOwnProperty.call(collection, key)) {
|
||||
values.push((collection as MapLike<T>)[key]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
namespace ts {
|
||||
// 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.
|
||||
export const versionMajorMinor = "4.5";
|
||||
export const versionMajorMinor = "4.7";
|
||||
// The following is baselined as a literal template type without intervention
|
||||
/** The version of the TypeScript compiler release */
|
||||
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
|
||||
@@ -113,17 +113,22 @@ namespace ts {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export namespace NativeCollections {
|
||||
declare const Map: MapConstructor | undefined;
|
||||
declare const Set: SetConstructor | undefined;
|
||||
namespace NativeCollections {
|
||||
declare const self: any;
|
||||
|
||||
const globals = typeof globalThis !== "undefined" ? globalThis :
|
||||
typeof global !== "undefined" ? global :
|
||||
typeof self !== "undefined" ? self :
|
||||
undefined;
|
||||
|
||||
/**
|
||||
* Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
|
||||
*/
|
||||
export function tryGetNativeMap(): MapConstructor | undefined {
|
||||
// Internet Explorer's Map doesn't support iteration, so don't use it.
|
||||
const gMap = globals?.Map;
|
||||
// eslint-disable-next-line no-in-operator
|
||||
return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined;
|
||||
return typeof gMap !== "undefined" && "entries" in gMap.prototype && new gMap([[0, 0]]).size === 1 ? gMap : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -131,8 +136,33 @@ namespace ts {
|
||||
*/
|
||||
export function tryGetNativeSet(): SetConstructor | undefined {
|
||||
// Internet Explorer's Set doesn't support iteration, so don't use it.
|
||||
const gSet = globals?.Set;
|
||||
// eslint-disable-next-line no-in-operator
|
||||
return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined;
|
||||
return typeof gSet !== "undefined" && "entries" in gSet.prototype && new gSet([0]).size === 1 ? gSet : undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
|
||||
/* @internal */
|
||||
export const Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
|
||||
|
||||
/* @internal */
|
||||
type GetIteratorCallback = <I extends readonly any[] | ReadonlySet<any> | ReadonlyESMap<any, any> | undefined>(iterable: I) => Iterator<
|
||||
I extends ReadonlyESMap<infer K, infer V> ? [K, V] :
|
||||
I extends ReadonlySet<infer T> ? T :
|
||||
I extends readonly (infer T)[] ? T :
|
||||
I extends undefined ? undefined :
|
||||
never>;
|
||||
|
||||
/* @internal */
|
||||
function getCollectionImplementation<
|
||||
K1 extends MatchingKeys<typeof NativeCollections, () => any>,
|
||||
K2 extends MatchingKeys<typeof ShimCollections, (getIterator?: GetIteratorCallback) => ReturnType<(typeof NativeCollections)[K1]>>
|
||||
>(name: string, nativeFactory: K1, shimFactory: K2): NonNullable<ReturnType<(typeof NativeCollections)[K1]>> {
|
||||
// NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
|
||||
const constructor = NativeCollections[nativeFactory]() ?? ShimCollections?.[shimFactory](getIterator);
|
||||
if (constructor) return constructor as NonNullable<ReturnType<(typeof NativeCollections)[K1]>>;
|
||||
throw new Error(`TypeScript requires an environment that provides a compatible native ${name} implementation.`);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-13
@@ -171,12 +171,6 @@ namespace ts {
|
||||
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>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction): asserts value is readonly NonNullable<T>[];
|
||||
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction) {
|
||||
@@ -190,12 +184,6 @@ namespace ts {
|
||||
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 {
|
||||
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);
|
||||
@@ -351,6 +339,10 @@ namespace ts {
|
||||
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 {
|
||||
return formatEnum(flags, (ts as any).NodeFlags, /*isFlags*/ true);
|
||||
}
|
||||
@@ -662,7 +654,7 @@ namespace ts {
|
||||
if (text === undefined) {
|
||||
const parseNode = getParseTreeNode(this);
|
||||
const sourceFile = parseNode && getSourceFileOfNode(parseNode);
|
||||
text = sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode!, includeTrivia) : "";
|
||||
text = sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
|
||||
map?.set(this, text);
|
||||
}
|
||||
return text;
|
||||
|
||||
@@ -335,7 +335,7 @@
|
||||
"category": "Error",
|
||||
"code": 1116
|
||||
},
|
||||
"An object literal cannot have multiple properties with the same name in strict mode.": {
|
||||
"An object literal cannot have multiple properties with the same name.": {
|
||||
"category": "Error",
|
||||
"code": 1117
|
||||
},
|
||||
@@ -727,11 +727,11 @@
|
||||
"category": "Error",
|
||||
"code": 1231
|
||||
},
|
||||
"An import declaration can only be used in a namespace or module.": {
|
||||
"An import declaration can only be used at the top level of a namespace or module.": {
|
||||
"category": "Error",
|
||||
"code": 1232
|
||||
},
|
||||
"An export declaration can only be used in a module.": {
|
||||
"An export declaration can only be used at the top level of a namespace or module.": {
|
||||
"category": "Error",
|
||||
"code": 1233
|
||||
},
|
||||
@@ -739,7 +739,7 @@
|
||||
"category": "Error",
|
||||
"code": 1234
|
||||
},
|
||||
"A namespace declaration is only allowed in a namespace or module.": {
|
||||
"A namespace declaration is only allowed at the top level of a namespace or module.": {
|
||||
"category": "Error",
|
||||
"code": 1235
|
||||
},
|
||||
@@ -867,6 +867,18 @@
|
||||
"category": "Error",
|
||||
"code": 1268
|
||||
},
|
||||
"Cannot use 'export import' on a type or type-only namespace when the '--isolatedModules' flag is provided.": {
|
||||
"category": "Error",
|
||||
"code": 1269
|
||||
},
|
||||
"Decorator function return type '{0}' is not assignable to type '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 1270
|
||||
},
|
||||
"Decorator function return type is '{0}' but is expected to be 'void' or 'any'.": {
|
||||
"category": "Error",
|
||||
"code": 1271
|
||||
},
|
||||
|
||||
"'with' statements are not allowed in an async function block.": {
|
||||
"category": "Error",
|
||||
@@ -920,15 +932,15 @@
|
||||
"category": "Error",
|
||||
"code": 1322
|
||||
},
|
||||
"Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'.": {
|
||||
"Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'es2022', 'esnext', 'commonjs', 'amd', 'system', 'umd', 'node12', or 'nodenext'.": {
|
||||
"category": "Error",
|
||||
"code": 1323
|
||||
},
|
||||
"Dynamic import must have one specifier as an argument.": {
|
||||
"Dynamic imports only support a second argument when the '--module' option is set to 'esnext' or 'nodenext'.": {
|
||||
"category": "Error",
|
||||
"code": 1324
|
||||
},
|
||||
"Specifier of dynamic import cannot be spread element.": {
|
||||
"Argument of dynamic import cannot be spread element.": {
|
||||
"category": "Error",
|
||||
"code": 1325
|
||||
},
|
||||
@@ -992,7 +1004,7 @@
|
||||
"category": "Error",
|
||||
"code": 1342
|
||||
},
|
||||
"The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.": {
|
||||
"The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node12', or 'nodenext'.": {
|
||||
"category": "Error",
|
||||
"code": 1343
|
||||
},
|
||||
@@ -1116,7 +1128,7 @@
|
||||
"category": "Message",
|
||||
"code": 1377
|
||||
},
|
||||
"Top-level 'await' expressions are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.": {
|
||||
"Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher.": {
|
||||
"category": "Error",
|
||||
"code": 1378
|
||||
},
|
||||
@@ -1140,10 +1152,6 @@
|
||||
"category": "Error",
|
||||
"code": 1383
|
||||
},
|
||||
"A 'new' expression with type arguments must always be followed by a parenthesized argument list.": {
|
||||
"category": "Error",
|
||||
"code": 1384
|
||||
},
|
||||
"Function type notation must be parenthesized when used in a union type.": {
|
||||
"category": "Error",
|
||||
"code": 1385
|
||||
@@ -1164,6 +1172,10 @@
|
||||
"category": "Error",
|
||||
"code": 1389
|
||||
},
|
||||
"'{0}' is not allowed as a parameter name.": {
|
||||
"category": "Error",
|
||||
"code": 1390
|
||||
},
|
||||
"An import alias cannot use 'import type'": {
|
||||
"category": "Error",
|
||||
"code": 1392
|
||||
@@ -1324,7 +1336,7 @@
|
||||
"category": "Error",
|
||||
"code": 1431
|
||||
},
|
||||
"Top-level 'for await' loops are only allowed when the 'module' option is set to 'esnext' or 'system', and the 'target' option is set to 'es2017' or higher.": {
|
||||
"Top-level 'for await' loops are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher.": {
|
||||
"category": "Error",
|
||||
"code": 1432
|
||||
},
|
||||
@@ -1388,6 +1400,43 @@
|
||||
"category": "Message",
|
||||
"code": 1449
|
||||
},
|
||||
"Dynamic imports can only accept a module specifier and an optional assertion as arguments": {
|
||||
"category": "Message",
|
||||
"code": 1450
|
||||
},
|
||||
"Private identifiers are only allowed in class bodies and may only be used as part of a class member declaration, property access, or on the left-hand-side of an 'in' expression": {
|
||||
"category": "Error",
|
||||
"code": 1451
|
||||
},
|
||||
"Resolution modes are only supported when `moduleResolution` is `node12` or `nodenext`.": {
|
||||
"category": "Error",
|
||||
"code": 1452
|
||||
},
|
||||
"`resolution-mode` should be either `require` or `import`.": {
|
||||
"category": "Error",
|
||||
"code": 1453
|
||||
},
|
||||
|
||||
"The 'import.meta' meta-property is not allowed in files which will build into CommonJS output.": {
|
||||
"category": "Error",
|
||||
"code": 1470
|
||||
},
|
||||
"Module '{0}' cannot be imported using this construct. The specifier only resolves to an ES module, which cannot be imported synchronously. Use dynamic import instead.": {
|
||||
"category": "Error",
|
||||
"code": 1471
|
||||
},
|
||||
"'catch' or 'finally' expected.": {
|
||||
"category": "Error",
|
||||
"code": 1472
|
||||
},
|
||||
"An import declaration can only be used at the top level of a module.": {
|
||||
"category": "Error",
|
||||
"code": 1473
|
||||
},
|
||||
"An export declaration can only be used at the top level of a module.": {
|
||||
"category": "Error",
|
||||
"code": 1474
|
||||
},
|
||||
|
||||
"The types of '{0}' are incompatible between these types.": {
|
||||
"category": "Error",
|
||||
@@ -1417,6 +1466,14 @@
|
||||
"code": 2205,
|
||||
"elidedInCompatabilityPyramid": true
|
||||
},
|
||||
"The 'type' modifier cannot be used on a named import when 'import type' is used on its import statement.": {
|
||||
"category": "Error",
|
||||
"code": 2206
|
||||
},
|
||||
"The 'type' modifier cannot be used on a named export when 'export type' is used on its export statement.": {
|
||||
"category": "Error",
|
||||
"code": 2207
|
||||
},
|
||||
|
||||
"Duplicate identifier '{0}'.": {
|
||||
"category": "Error",
|
||||
@@ -1462,6 +1519,10 @@
|
||||
"category": "Error",
|
||||
"code": 2310
|
||||
},
|
||||
"Cannot find name '{0}'. Did you mean to write this in an async function?": {
|
||||
"category": "Error",
|
||||
"code": 2311
|
||||
},
|
||||
"An interface can only extend an object type or intersection of object types with statically known members.": {
|
||||
"category": "Error",
|
||||
"code": 2312
|
||||
@@ -1650,7 +1711,7 @@
|
||||
"category": "Error",
|
||||
"code": 2359
|
||||
},
|
||||
"The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'.": {
|
||||
"The left-hand side of an 'in' expression must be a private identifier or of type 'any', 'string', 'number', or 'symbol'.": {
|
||||
"category": "Error",
|
||||
"code": 2360
|
||||
},
|
||||
@@ -1714,7 +1775,7 @@
|
||||
"category": "Error",
|
||||
"code": 2375
|
||||
},
|
||||
"A 'super' call must be the first statement in the constructor when a class contains initialized properties, parameter properties, or private identifiers.": {
|
||||
"A 'super' call must be the first statement in the constructor to refer to 'super' or 'this' when a derived class contains initialized properties, parameter properties, or private identifiers.": {
|
||||
"category": "Error",
|
||||
"code": 2376
|
||||
},
|
||||
@@ -1806,6 +1867,10 @@
|
||||
"category": "Error",
|
||||
"code": 2400
|
||||
},
|
||||
"A 'super' call must be a root-level statement within a constructor of a derived class that contains initialized properties, parameter properties, or private identifiers.": {
|
||||
"category": "Error",
|
||||
"code": 2401
|
||||
},
|
||||
"Expression resolves to '_super' that compiler uses to capture base class reference.": {
|
||||
"category": "Error",
|
||||
"code": 2402
|
||||
@@ -2634,6 +2699,10 @@
|
||||
"category": "Error",
|
||||
"code": 2634
|
||||
},
|
||||
"Type '{0}' has no signatures for which the type argument list is applicable.": {
|
||||
"category": "Error",
|
||||
"code": 2635
|
||||
},
|
||||
|
||||
"Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": {
|
||||
"category": "Error",
|
||||
@@ -3240,10 +3309,6 @@
|
||||
"category": "Error",
|
||||
"code": 2804
|
||||
},
|
||||
"Static fields with private names can't have initializers when the '--useDefineForClassFields' flag is not specified with a '--target' of 'esnext'. Consider adding the '--useDefineForClassFields' flag.": {
|
||||
"category": "Error",
|
||||
"code": 2805
|
||||
},
|
||||
"Private accessor was defined without a getter.": {
|
||||
"category": "Error",
|
||||
"code": 2806
|
||||
@@ -3260,10 +3325,6 @@
|
||||
"category": "Error",
|
||||
"code": 2809
|
||||
},
|
||||
"Property '{0}' may not be used in a static property's initializer in the same class when 'target' is 'esnext' and 'useDefineForClassFields' is 'false'.": {
|
||||
"category": "Error",
|
||||
"code": 2810
|
||||
},
|
||||
"Initializer for property '{0}'": {
|
||||
"category": "Error",
|
||||
"code": 2811
|
||||
@@ -3300,6 +3361,38 @@
|
||||
"category": "Error",
|
||||
"code": 2819
|
||||
},
|
||||
"Type '{0}' is not assignable to type '{1}'. Did you mean '{2}'?": {
|
||||
"category": "Error",
|
||||
"code": 2820
|
||||
},
|
||||
"Import assertions are only supported when the '--module' option is set to 'esnext' or 'nodenext'.": {
|
||||
"category": "Error",
|
||||
"code": 2821
|
||||
},
|
||||
"Import assertions cannot be used with type-only imports or exports.": {
|
||||
"category": "Error",
|
||||
"code": 2822
|
||||
},
|
||||
"Cannot find namespace '{0}'. Did you mean '{1}'?": {
|
||||
"category": "Error",
|
||||
"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 assertion values must be string literal expressions.": {
|
||||
"category": "Error",
|
||||
"code": 2837
|
||||
},
|
||||
|
||||
"Import declaration '{0}' is using private name '{1}'.": {
|
||||
"category": "Error",
|
||||
@@ -3705,6 +3798,30 @@
|
||||
"category": "Error",
|
||||
"code": 4118
|
||||
},
|
||||
"This member must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'.": {
|
||||
"category": "Error",
|
||||
"code": 4119
|
||||
},
|
||||
"This parameter property must have a JSDoc comment with an '@override' tag because it overrides a member in the base class '{0}'.": {
|
||||
"category": "Error",
|
||||
"code": 4120
|
||||
},
|
||||
"This member cannot have a JSDoc comment with an '@override' tag because its containing class '{0}' does not extend another class.": {
|
||||
"category": "Error",
|
||||
"code": 4121
|
||||
},
|
||||
"This member cannot have a JSDoc comment with an '@override' tag because it is not declared in the base class '{0}'.": {
|
||||
"category": "Error",
|
||||
"code": 4122
|
||||
},
|
||||
"This member cannot have a JSDoc comment with an 'override' tag because it is not declared in the base class '{0}'. Did you mean '{1}'?": {
|
||||
"category": "Error",
|
||||
"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.": {
|
||||
"category": "Error",
|
||||
@@ -3943,10 +4060,6 @@
|
||||
"category": "Message",
|
||||
"code": 6002
|
||||
},
|
||||
"Specify the location where debugger should locate map files instead of generated locations.": {
|
||||
"category": "Message",
|
||||
"code": 6003
|
||||
},
|
||||
"Specify the location where debugger should locate TypeScript files instead of source locations.": {
|
||||
"category": "Message",
|
||||
"code": 6004
|
||||
@@ -4075,6 +4188,11 @@
|
||||
"category": "Message",
|
||||
"code": 6040
|
||||
},
|
||||
"Errors Files": {
|
||||
"_locale_notes": "There is a double space, and the order cannot be changed (they're table headings) ^",
|
||||
"category": "Message",
|
||||
"code": 6041
|
||||
},
|
||||
"Generates corresponding '.map' file.": {
|
||||
"category": "Message",
|
||||
"code": 6043
|
||||
@@ -4513,10 +4631,6 @@
|
||||
"category": "Message",
|
||||
"code": 6163
|
||||
},
|
||||
"Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.": {
|
||||
"category": "Message",
|
||||
"code": 6164
|
||||
},
|
||||
"Do not truncate error messages.": {
|
||||
"category": "Message",
|
||||
"code": 6165
|
||||
@@ -4858,6 +4972,47 @@
|
||||
"category": "Error",
|
||||
"code": 6258
|
||||
},
|
||||
"Found 1 error in {1}": {
|
||||
"category": "Message",
|
||||
"code": 6259
|
||||
},
|
||||
"Found {0} errors in the same file, starting at: {1}": {
|
||||
"category": "Message",
|
||||
"code": 6260
|
||||
},
|
||||
"Found {0} errors in {1} files.": {
|
||||
"category": "Message",
|
||||
"code": 6261
|
||||
},
|
||||
|
||||
"Directory '{0}' has no containing package.json scope. Imports will not resolve.": {
|
||||
"category": "Message",
|
||||
"code": 6270
|
||||
},
|
||||
"Import specifier '{0}' does not exist in package.json scope at path '{1}'.": {
|
||||
"category": "Message",
|
||||
"code": 6271
|
||||
},
|
||||
"Invalid import specifier '{0}' has no possible resolutions.": {
|
||||
"category": "Message",
|
||||
"code": 6272
|
||||
},
|
||||
"package.json scope '{0}' has no imports defined.": {
|
||||
"category": "Message",
|
||||
"code": 6273
|
||||
},
|
||||
"package.json scope '{0}' explicitly maps specifier '{1}' to null.": {
|
||||
"category": "Message",
|
||||
"code": 6274
|
||||
},
|
||||
"package.json scope '{0}' has invalid type for target of specifier '{1}'": {
|
||||
"category": "Message",
|
||||
"code": 6275
|
||||
},
|
||||
"Export specifier '{0}' does not exist in package.json scope at path '{1}'.": {
|
||||
"category": "Message",
|
||||
"code": 6276
|
||||
},
|
||||
|
||||
"Enable project compilation": {
|
||||
"category": "Message",
|
||||
@@ -5904,7 +6059,22 @@
|
||||
"category": "Error",
|
||||
"code": 7058
|
||||
},
|
||||
|
||||
"This syntax is reserved in files with the .mts or .cts extension. Use an `as` expression instead.": {
|
||||
"category": "Error",
|
||||
"code": 7059
|
||||
},
|
||||
"This syntax is reserved in files with the .mts or .cts extension. Add a trailing comma or explicit constraint.": {
|
||||
"category": "Error",
|
||||
"code": 7060
|
||||
},
|
||||
"A mapped type may not declare properties or methods.": {
|
||||
"category": "Error",
|
||||
"code": 7061
|
||||
},
|
||||
"JSON imports are experimental in ES module mode imports.": {
|
||||
"category": "Error",
|
||||
"code": 7062
|
||||
},
|
||||
|
||||
"You cannot rename this element.": {
|
||||
"category": "Error",
|
||||
@@ -6127,7 +6297,7 @@
|
||||
"code": 18003
|
||||
},
|
||||
|
||||
"File is a CommonJS module; it may be converted to an ES6 module.": {
|
||||
"File is a CommonJS module; it may be converted to an ES module.": {
|
||||
"category": "Suggestion",
|
||||
"code": 80001
|
||||
},
|
||||
@@ -6204,7 +6374,7 @@
|
||||
"category": "Message",
|
||||
"code": 90012
|
||||
},
|
||||
"Import '{0}' from module \"{1}\"": {
|
||||
"Import '{0}' from \"{1}\"": {
|
||||
"category": "Message",
|
||||
"code": 90013
|
||||
},
|
||||
@@ -6212,10 +6382,6 @@
|
||||
"category": "Message",
|
||||
"code": 90014
|
||||
},
|
||||
"Add '{0}' to existing import declaration from \"{1}\"": {
|
||||
"category": "Message",
|
||||
"code": 90015
|
||||
},
|
||||
"Declare property '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 90016
|
||||
@@ -6280,14 +6446,6 @@
|
||||
"category": "Message",
|
||||
"code": 90031
|
||||
},
|
||||
"Import default '{0}' from module \"{1}\"": {
|
||||
"category": "Message",
|
||||
"code": 90032
|
||||
},
|
||||
"Add default import '{0}' to existing import declaration from \"{1}\"": {
|
||||
"category": "Message",
|
||||
"code": 90033
|
||||
},
|
||||
"Add parameter name": {
|
||||
"category": "Message",
|
||||
"code": 90034
|
||||
@@ -6320,6 +6478,27 @@
|
||||
"category": "Message",
|
||||
"code": 90053
|
||||
},
|
||||
"Includes imports of types referenced by '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 90054
|
||||
},
|
||||
"Remove 'type' from import declaration from \"{0}\"": {
|
||||
"category": "Message",
|
||||
"code": 90055
|
||||
},
|
||||
"Remove 'type' from import of '{0}' from \"{1}\"": {
|
||||
"category": "Message",
|
||||
"code": 90056
|
||||
},
|
||||
"Add import from \"{0}\"": {
|
||||
"category": "Message",
|
||||
"code": 90057
|
||||
},
|
||||
"Update import from \"{0}\"": {
|
||||
"category": "Message",
|
||||
"code": 90058
|
||||
},
|
||||
|
||||
"Convert function to an ES2015 class": {
|
||||
"category": "Message",
|
||||
"code": 95001
|
||||
@@ -6376,7 +6555,7 @@
|
||||
"category": "Message",
|
||||
"code": 95016
|
||||
},
|
||||
"Convert to ES6 module": {
|
||||
"Convert to ES module": {
|
||||
"category": "Message",
|
||||
"code": 95017
|
||||
},
|
||||
@@ -6972,6 +7151,22 @@
|
||||
"category": "Message",
|
||||
"code": 95169
|
||||
},
|
||||
"Convert named imports to default import": {
|
||||
"category": "Message",
|
||||
"code": 95170
|
||||
},
|
||||
"Delete unused '@param' tag '{0}'": {
|
||||
"category": "Message",
|
||||
"code": 95171
|
||||
},
|
||||
"Delete all unused '@param' tags": {
|
||||
"category": "Message",
|
||||
"code": 95172
|
||||
},
|
||||
"Rename '@param' tag name '{0}' to '{1}'": {
|
||||
"category": "Message",
|
||||
"code": 95173
|
||||
},
|
||||
|
||||
"No value exists in scope for the shorthand property '{0}'. Either declare one or provide an initializer.": {
|
||||
"category": "Error",
|
||||
|
||||
+158
-42
@@ -89,7 +89,7 @@ namespace ts {
|
||||
return getOutputPathsForBundle(options, forceDtsPaths);
|
||||
}
|
||||
else {
|
||||
const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
|
||||
const ownOutputFilePath = getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile.fileName, options));
|
||||
const isJsonFile = isJsonSourceFile(sourceFile);
|
||||
// If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
|
||||
const isJsonEmittedToSameLocation = isJsonFile &&
|
||||
@@ -106,27 +106,13 @@ namespace ts {
|
||||
return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
|
||||
}
|
||||
|
||||
// JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
|
||||
// So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
|
||||
// For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
|
||||
/* @internal */
|
||||
export function getOutputExtension(sourceFile: SourceFile, options: CompilerOptions): Extension {
|
||||
if (isJsonSourceFile(sourceFile)) {
|
||||
return Extension.Json;
|
||||
}
|
||||
|
||||
if (options.jsx === JsxEmit.Preserve) {
|
||||
if (isSourceFileJS(sourceFile)) {
|
||||
if (fileExtensionIs(sourceFile.fileName, Extension.Jsx)) {
|
||||
return Extension.Jsx;
|
||||
}
|
||||
}
|
||||
else if (sourceFile.languageVariant === LanguageVariant.JSX) {
|
||||
// TypeScript source file preserving JSX syntax
|
||||
return Extension.Jsx;
|
||||
}
|
||||
}
|
||||
return Extension.Js;
|
||||
export function getOutputExtension(fileName: string, options: CompilerOptions): Extension {
|
||||
return fileExtensionIs(fileName, Extension.Json) ? Extension.Json :
|
||||
options.jsx === JsxEmit.Preserve && fileExtensionIsOneOf(fileName, [Extension.Jsx, Extension.Tsx]) ? Extension.Jsx :
|
||||
fileExtensionIsOneOf(fileName, [Extension.Mts, Extension.Mjs]) ? Extension.Mjs :
|
||||
fileExtensionIsOneOf(fileName, [Extension.Cts, Extension.Cjs]) ? Extension.Cjs :
|
||||
Extension.Js;
|
||||
}
|
||||
|
||||
function getOutputPathWithoutChangingExt(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, outputDir: string | undefined, getCommonSourceDirectory?: () => string) {
|
||||
@@ -140,10 +126,9 @@ namespace ts {
|
||||
|
||||
/* @internal */
|
||||
export function getOutputDeclarationFileName(inputFileName: string, configFile: ParsedCommandLine, ignoreCase: boolean, getCommonSourceDirectory?: () => string) {
|
||||
Debug.assert(!fileExtensionIs(inputFileName, Extension.Dts) && !fileExtensionIs(inputFileName, Extension.Json));
|
||||
return changeExtension(
|
||||
getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir, getCommonSourceDirectory),
|
||||
Extension.Dts
|
||||
getDeclarationEmitExtensionForPath(inputFileName)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -152,11 +137,7 @@ namespace ts {
|
||||
const isJsonFile = fileExtensionIs(inputFileName, Extension.Json);
|
||||
const outputFileName = changeExtension(
|
||||
getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir, getCommonSourceDirectory),
|
||||
isJsonFile ?
|
||||
Extension.Json :
|
||||
configFile.options.jsx === JsxEmit.Preserve && (fileExtensionIs(inputFileName, Extension.Tsx) || fileExtensionIs(inputFileName, Extension.Jsx)) ?
|
||||
Extension.Jsx :
|
||||
Extension.Js
|
||||
getOutputExtension(inputFileName, configFile.options)
|
||||
);
|
||||
return !isJsonFile || comparePaths(inputFileName, outputFileName, Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== Comparison.EqualTo ?
|
||||
outputFileName :
|
||||
@@ -238,7 +219,7 @@ namespace ts {
|
||||
export function getCommonSourceDirectoryOfConfig({ options, fileNames }: ParsedCommandLine, ignoreCase: boolean): string {
|
||||
return getCommonSourceDirectory(
|
||||
options,
|
||||
() => filter(fileNames, file => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensions)) && !fileExtensionIs(file, Extension.Dts)),
|
||||
() => filter(fileNames, file => !(options.noEmitForJsFiles && fileExtensionIsOneOf(file, supportedJSExtensionsFlat)) && !fileExtensionIs(file, Extension.Dts)),
|
||||
getDirectoryPath(normalizeSlashes(Debug.checkDefined(options.configFilePath))),
|
||||
createGetCanonicalFileName(!ignoreCase)
|
||||
);
|
||||
@@ -1070,7 +1051,7 @@ namespace ts {
|
||||
writeLine();
|
||||
const pos = writer.getTextPos();
|
||||
const savedSections = bundleFileInfo && bundleFileInfo.sections;
|
||||
if (savedSections) bundleFileInfo!.sections = [];
|
||||
if (savedSections) bundleFileInfo.sections = [];
|
||||
print(EmitHint.Unspecified, prepend, /*sourceFile*/ undefined);
|
||||
if (bundleFileInfo) {
|
||||
const newSections = bundleFileInfo.sections;
|
||||
@@ -1302,7 +1283,13 @@ namespace ts {
|
||||
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.IdentifierName) return emitIdentifier(cast(node, isIdentifier));
|
||||
if (hint === EmitHint.JsxAttributeValue) return emitLiteral(cast(node, isStringLiteral), /*jsxAttributeEscape*/ true);
|
||||
@@ -1515,6 +1502,10 @@ namespace ts {
|
||||
return emitNamedExports(node as NamedExports);
|
||||
case SyntaxKind.ExportSpecifier:
|
||||
return emitExportSpecifier(node as ExportSpecifier);
|
||||
case SyntaxKind.AssertClause:
|
||||
return emitAssertClause(node as AssertClause);
|
||||
case SyntaxKind.AssertEntry:
|
||||
return emitAssertEntry(node as AssertEntry);
|
||||
case SyntaxKind.MissingDeclaration:
|
||||
return;
|
||||
|
||||
@@ -1613,6 +1604,7 @@ namespace ts {
|
||||
return emitJSDocSignature(node as JSDocSignature);
|
||||
case SyntaxKind.JSDocTag:
|
||||
case SyntaxKind.JSDocClassTag:
|
||||
case SyntaxKind.JSDocOverrideTag:
|
||||
return emitJSDocSimpleTag(node as JSDocTag);
|
||||
case SyntaxKind.JSDocAugmentsTag:
|
||||
case SyntaxKind.JSDocImplementsTag:
|
||||
@@ -1625,7 +1617,6 @@ namespace ts {
|
||||
case SyntaxKind.JSDocPrivateTag:
|
||||
case SyntaxKind.JSDocProtectedTag:
|
||||
case SyntaxKind.JSDocReadonlyTag:
|
||||
case SyntaxKind.JSDocOverrideTag:
|
||||
return;
|
||||
case SyntaxKind.JSDocCallbackTag:
|
||||
return emitJSDocCallbackTag(node as JSDocCallbackTag);
|
||||
@@ -1680,6 +1671,8 @@ namespace ts {
|
||||
// Identifiers
|
||||
case SyntaxKind.Identifier:
|
||||
return emitIdentifier(node as Identifier);
|
||||
case SyntaxKind.PrivateIdentifier:
|
||||
return emitPrivateIdentifier(node as PrivateIdentifier);
|
||||
|
||||
// Expressions
|
||||
case SyntaxKind.ArrayLiteralExpression:
|
||||
@@ -1734,6 +1727,8 @@ namespace ts {
|
||||
return emitAsExpression(node as AsExpression);
|
||||
case SyntaxKind.NonNullExpression:
|
||||
return emitNonNullExpression(node as NonNullExpression);
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
|
||||
case SyntaxKind.MetaProperty:
|
||||
return emitMetaProperty(node as MetaProperty);
|
||||
case SyntaxKind.SyntheticExpression:
|
||||
@@ -1937,6 +1932,37 @@ 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(hint, node, snippet);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function emitPlaceholder(hint: EmitHint, node: Node, snippet: Placeholder) {
|
||||
nonEscapingWrite(`\$\{${snippet.order}:`); // `${2:`
|
||||
pipelineEmitWithHintWorker(hint, node, /*allowSnippets*/ false); // `...`
|
||||
nonEscapingWrite(`\}`); // `}`
|
||||
// `${2:...}`
|
||||
}
|
||||
|
||||
function emitTabStop(hint: EmitHint, node: Node, snippet: TabStop) {
|
||||
// A tab stop should only be attached to an empty node, i.e. a node that doesn't emit any text.
|
||||
Debug.assert(node.kind === SyntaxKind.EmptyStatement,
|
||||
`A tab stop cannot be attached to a node of kind ${Debug.formatSyntaxKind(node.kind)}.`);
|
||||
Debug.assert(hint !== EmitHint.EmbeddedStatement,
|
||||
`A tab stop cannot be attached to an embedded statement.`);
|
||||
nonEscapingWrite(`\$${snippet.order}`);
|
||||
}
|
||||
|
||||
//
|
||||
// Identifiers
|
||||
//
|
||||
@@ -2203,6 +2229,7 @@ namespace ts {
|
||||
writeKeyword("typeof");
|
||||
writeSpace();
|
||||
emit(node.exprName);
|
||||
emitTypeArguments(node, node.typeArguments);
|
||||
}
|
||||
|
||||
function emitTypeLiteral(node: TypeLiteralNode) {
|
||||
@@ -2747,7 +2774,7 @@ namespace ts {
|
||||
function emitYieldExpression(node: YieldExpression) {
|
||||
emitTokenWithComment(SyntaxKind.YieldKeyword, node.pos, writeKeyword, node);
|
||||
emit(node.asteriskToken);
|
||||
emitExpressionWithLeadingSpace(node.expression, parenthesizer.parenthesizeExpressionForDisallowedComma);
|
||||
emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsiAndDisallowedComma);
|
||||
}
|
||||
|
||||
function emitSpreadElement(node: SpreadElement) {
|
||||
@@ -2971,9 +2998,49 @@ namespace ts {
|
||||
return pos;
|
||||
}
|
||||
|
||||
function commentWillEmitNewLine(node: CommentRange) {
|
||||
return node.kind === SyntaxKind.SingleLineCommentTrivia || !!node.hasTrailingNewLine;
|
||||
}
|
||||
|
||||
function willEmitLeadingNewLine(node: Expression): boolean {
|
||||
if (!currentSourceFile) return false;
|
||||
if (some(getLeadingCommentRanges(currentSourceFile.text, node.pos), commentWillEmitNewLine)) return true;
|
||||
if (some(getSyntheticLeadingComments(node), commentWillEmitNewLine)) return true;
|
||||
if (isPartiallyEmittedExpression(node)) {
|
||||
if (node.pos !== node.expression.pos) {
|
||||
if (some(getTrailingCommentRanges(currentSourceFile.text, node.expression.pos), commentWillEmitNewLine)) return true;
|
||||
}
|
||||
return willEmitLeadingNewLine(node.expression);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an expression in parens if we would emit a leading comment that would introduce a line separator
|
||||
* between the node and its parent.
|
||||
*/
|
||||
function parenthesizeExpressionForNoAsi(node: Expression) {
|
||||
if (!commentsDisabled && isPartiallyEmittedExpression(node) && willEmitLeadingNewLine(node)) {
|
||||
const parseNode = getParseTreeNode(node);
|
||||
if (parseNode && isParenthesizedExpression(parseNode)) {
|
||||
// If the original node was a parenthesized expression, restore it to preserve comment and source map emit
|
||||
const parens = factory.createParenthesizedExpression(node.expression);
|
||||
setOriginalNode(parens, node);
|
||||
setTextRange(parens, parseNode);
|
||||
return parens;
|
||||
}
|
||||
return factory.createParenthesizedExpression(node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
function parenthesizeExpressionForNoAsiAndDisallowedComma(node: Expression) {
|
||||
return parenthesizeExpressionForNoAsi(parenthesizer.parenthesizeExpressionForDisallowedComma(node));
|
||||
}
|
||||
|
||||
function emitReturnStatement(node: ReturnStatement) {
|
||||
emitTokenWithComment(SyntaxKind.ReturnKeyword, node.pos, writeKeyword, /*contextNode*/ node);
|
||||
emitExpressionWithLeadingSpace(node.expression);
|
||||
emitExpressionWithLeadingSpace(node.expression && parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi);
|
||||
writeTrailingSemicolon();
|
||||
}
|
||||
|
||||
@@ -3005,7 +3072,7 @@ namespace ts {
|
||||
|
||||
function emitThrowStatement(node: ThrowStatement) {
|
||||
emitTokenWithComment(SyntaxKind.ThrowKeyword, node.pos, writeKeyword, node);
|
||||
emitExpressionWithLeadingSpace(node.expression);
|
||||
emitExpressionWithLeadingSpace(parenthesizeExpressionForNoAsi(node.expression), parenthesizeExpressionForNoAsi);
|
||||
writeTrailingSemicolon();
|
||||
}
|
||||
|
||||
@@ -3322,6 +3389,9 @@ namespace ts {
|
||||
writeSpace();
|
||||
}
|
||||
emitExpression(node.moduleSpecifier);
|
||||
if (node.assertClause) {
|
||||
emitWithLeadingSpace(node.assertClause);
|
||||
}
|
||||
writeTrailingSemicolon();
|
||||
}
|
||||
|
||||
@@ -3390,9 +3460,33 @@ namespace ts {
|
||||
writeSpace();
|
||||
emitExpression(node.moduleSpecifier);
|
||||
}
|
||||
if (node.assertClause) {
|
||||
emitWithLeadingSpace(node.assertClause);
|
||||
}
|
||||
writeTrailingSemicolon();
|
||||
}
|
||||
|
||||
function emitAssertClause(node: AssertClause) {
|
||||
emitTokenWithComment(SyntaxKind.AssertKeyword, node.pos, writeKeyword, node);
|
||||
writeSpace();
|
||||
const elements = node.elements;
|
||||
emitList(node, elements, ListFormat.ImportClauseEntries);
|
||||
}
|
||||
|
||||
function emitAssertEntry(node: AssertEntry) {
|
||||
emit(node.name);
|
||||
writePunctuation(":");
|
||||
writeSpace();
|
||||
|
||||
const value = node.value;
|
||||
/** @see {emitPropertyAssignment} */
|
||||
if ((getEmitFlags(value) & EmitFlags.NoLeadingComments) === 0) {
|
||||
const commentRange = getCommentRange(value);
|
||||
emitTrailingCommentsOfPosition(commentRange.pos);
|
||||
}
|
||||
emit(value);
|
||||
}
|
||||
|
||||
function emitNamespaceExportDeclaration(node: NamespaceExportDeclaration) {
|
||||
let nextPos = emitTokenWithComment(SyntaxKind.ExportKeyword, node.pos, writeKeyword, node);
|
||||
writeSpace();
|
||||
@@ -3427,6 +3521,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
function emitImportOrExportSpecifier(node: ImportOrExportSpecifier) {
|
||||
if (node.isTypeOnly) {
|
||||
writeKeyword("type");
|
||||
writeSpace();
|
||||
}
|
||||
if (node.propertyName) {
|
||||
emit(node.propertyName);
|
||||
writeSpace();
|
||||
@@ -3898,8 +3996,11 @@ namespace ts {
|
||||
}
|
||||
for (const directive of types) {
|
||||
const pos = writer.getTextPos();
|
||||
writeComment(`/// <reference types="${directive.fileName}" />`);
|
||||
if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: BundleFileSectionKind.Type, data: directive.fileName });
|
||||
const resolutionMode = directive.resolutionMode && directive.resolutionMode !== currentSourceFile?.impliedNodeFormat
|
||||
? `resolution-mode="${directive.resolutionMode === ModuleKind.ESNext ? "import" : "require"}"`
|
||||
: "";
|
||||
writeComment(`/// <reference types="${directive.fileName}" ${resolutionMode}/>`);
|
||||
if (bundleFileInfo) bundleFileInfo.sections.push({ pos, end: writer.getTextPos(), kind: !directive.resolutionMode ? BundleFileSectionKind.Type : directive.resolutionMode === ModuleKind.ESNext ? BundleFileSectionKind.TypeResolutionModeImport : BundleFileSectionKind.TypeResolutionModeRequire, data: directive.fileName });
|
||||
writeLine();
|
||||
}
|
||||
for (const directive of libs) {
|
||||
@@ -3924,7 +4025,14 @@ namespace ts {
|
||||
// Transformation nodes
|
||||
|
||||
function emitPartiallyEmittedExpression(node: PartiallyEmittedExpression) {
|
||||
const emitFlags = getEmitFlags(node);
|
||||
if (!(emitFlags & EmitFlags.NoLeadingComments) && node.pos !== node.expression.pos) {
|
||||
emitTrailingCommentsOfPosition(node.expression.pos);
|
||||
}
|
||||
emitExpression(node.expression);
|
||||
if (!(emitFlags & EmitFlags.NoTrailingComments) && node.end !== node.expression.end) {
|
||||
emitLeadingCommentsOfPosition(node.expression.end);
|
||||
}
|
||||
}
|
||||
|
||||
function emitCommaList(node: CommaListExpression) {
|
||||
@@ -4312,10 +4420,8 @@ namespace ts {
|
||||
// Emit this child.
|
||||
previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
|
||||
if (shouldEmitInterveningComments) {
|
||||
if (emitTrailingCommentsOfPosition) {
|
||||
const commentRange = getCommentRange(child);
|
||||
emitTrailingCommentsOfPosition(commentRange.pos);
|
||||
}
|
||||
const commentRange = getCommentRange(child);
|
||||
emitTrailingCommentsOfPosition(commentRange.pos);
|
||||
}
|
||||
else {
|
||||
shouldEmitInterveningComments = mayEmitInterveningComments;
|
||||
@@ -4439,6 +4545,16 @@ namespace ts {
|
||||
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) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
writer.writeLine(i > 0);
|
||||
@@ -4683,7 +4799,7 @@ namespace ts {
|
||||
function writeLineSeparatorsAndIndentBefore(node: Node, parent: Node): boolean {
|
||||
const leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], ListFormat.None);
|
||||
if (leadingNewlines) {
|
||||
writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
|
||||
writeLinesAndIndent(leadingNewlines, /*writeSpaceIfNotIndenting*/ false);
|
||||
}
|
||||
return !!leadingNewlines;
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ namespace ts {
|
||||
// Class Fields Helpers
|
||||
createClassPrivateFieldGetHelper(receiver: Expression, state: Identifier, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression;
|
||||
createClassPrivateFieldSetHelper(receiver: Expression, state: Identifier, value: Expression, kind: PrivateIdentifierKind, f: Identifier | undefined): Expression;
|
||||
createClassPrivateFieldInHelper(state: Identifier, receiver: Expression): Expression;
|
||||
}
|
||||
|
||||
export function createEmitHelperFactory(context: TransformationContext): EmitHelperFactory {
|
||||
@@ -75,6 +76,7 @@ namespace ts {
|
||||
// Class Fields Helpers
|
||||
createClassPrivateFieldGetHelper,
|
||||
createClassPrivateFieldSetHelper,
|
||||
createClassPrivateFieldInHelper
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -136,7 +138,7 @@ namespace ts {
|
||||
// ES2018 Helpers
|
||||
|
||||
function createAssignHelper(attributesSegments: Expression[]) {
|
||||
if (context.getCompilerOptions().target! >= ScriptTarget.ES2015) {
|
||||
if (getEmitScriptTarget(context.getCompilerOptions()) >= ScriptTarget.ES2015) {
|
||||
return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"),
|
||||
/*typeArguments*/ undefined,
|
||||
attributesSegments);
|
||||
@@ -395,6 +397,10 @@ namespace ts {
|
||||
return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, args);
|
||||
}
|
||||
|
||||
function createClassPrivateFieldInHelper(state: Identifier, receiver: Expression) {
|
||||
context.requestEmitHelper(classPrivateFieldInHelper);
|
||||
return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldIn"), /* typeArguments*/ undefined, [state, receiver]);
|
||||
}
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -777,7 +783,11 @@ namespace ts {
|
||||
text: `
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
@@ -961,6 +971,29 @@ namespace ts {
|
||||
};`
|
||||
};
|
||||
|
||||
/**
|
||||
* Parameters:
|
||||
* @param state — One of the following:
|
||||
* - A WeakMap when the member is a private instance field.
|
||||
* - A WeakSet when the member is a private instance method or accessor.
|
||||
* - A function value that should be the undecorated class constructor when the member is a private static field, method, or accessor.
|
||||
* @param receiver — The object being checked if it has the private member.
|
||||
*
|
||||
* Usage:
|
||||
* This helper is used to transform `#field in expression` to
|
||||
* `__classPrivateFieldIn(<weakMap/weakSet/constructor>, expression)`
|
||||
*/
|
||||
export const classPrivateFieldInHelper: UnscopedEmitHelper = {
|
||||
name: "typescript:classPrivateFieldIn",
|
||||
importName: "__classPrivateFieldIn",
|
||||
scoped: false,
|
||||
text: `
|
||||
var __classPrivateFieldIn = (this && this.__classPrivateFieldIn) || function(state, receiver) {
|
||||
if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
|
||||
return typeof state === "function" ? receiver === state : state.has(receiver);
|
||||
};`
|
||||
};
|
||||
|
||||
let allUnscopedEmitHelpers: ReadonlyESMap<string, UnscopedEmitHelper> | undefined;
|
||||
|
||||
export function getAllUnscopedEmitHelpers() {
|
||||
@@ -986,6 +1019,7 @@ namespace ts {
|
||||
exportStarHelper,
|
||||
classPrivateFieldGetHelper,
|
||||
classPrivateFieldSetHelper,
|
||||
classPrivateFieldInHelper,
|
||||
createBindingHelper,
|
||||
setModuleDefaultHelper
|
||||
], helper => helper.name));
|
||||
|
||||
@@ -127,7 +127,7 @@ namespace ts {
|
||||
/**
|
||||
* Gets a custom text range to use when emitting comments.
|
||||
*/
|
||||
export function getCommentRange(node: Node) {
|
||||
export function getCommentRange(node: Node): TextRange {
|
||||
return node.emitNode?.commentRange ?? node;
|
||||
}
|
||||
|
||||
@@ -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 */
|
||||
export function ignoreSourceNewlines<T extends Node>(node: T): T {
|
||||
getOrCreateEmitNode(node).flags |= EmitFlags.IgnoreSourceNewlines;
|
||||
|
||||
@@ -289,6 +289,10 @@ namespace ts {
|
||||
updateImportDeclaration,
|
||||
createImportClause,
|
||||
updateImportClause,
|
||||
createAssertClause,
|
||||
updateAssertClause,
|
||||
createAssertEntry,
|
||||
updateAssertEntry,
|
||||
createNamespaceImport,
|
||||
updateNamespaceImport,
|
||||
createNamespaceExport,
|
||||
@@ -1071,7 +1075,7 @@ namespace ts {
|
||||
if (flags & ModifierFlags.Override) result.push(createModifier(SyntaxKind.OverrideKeyword));
|
||||
if (flags & ModifierFlags.Readonly) result.push(createModifier(SyntaxKind.ReadonlyKeyword));
|
||||
if (flags & ModifierFlags.Async) result.push(createModifier(SyntaxKind.AsyncKeyword));
|
||||
return result;
|
||||
return result.length ? result : undefined;
|
||||
}
|
||||
|
||||
//
|
||||
@@ -1835,17 +1839,19 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @api
|
||||
function createTypeQueryNode(exprName: EntityName) {
|
||||
function createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]) {
|
||||
const node = createBaseNode<TypeQueryNode>(SyntaxKind.TypeQuery);
|
||||
node.exprName = exprName;
|
||||
node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
|
||||
node.transformFlags = TransformFlags.ContainsTypeScript;
|
||||
return node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName) {
|
||||
function updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]) {
|
||||
return node.exprName !== exprName
|
||||
? update(createTypeQueryNode(exprName), node)
|
||||
|| node.typeArguments !== typeArguments
|
||||
? update(createTypeQueryNode(exprName, typeArguments), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
@@ -2108,25 +2114,27 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @api
|
||||
function createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode {
|
||||
function createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: readonly TypeElement[] | undefined): MappedTypeNode {
|
||||
const node = createBaseNode<MappedTypeNode>(SyntaxKind.MappedType);
|
||||
node.readonlyToken = readonlyToken;
|
||||
node.typeParameter = typeParameter;
|
||||
node.nameType = nameType;
|
||||
node.questionToken = questionToken;
|
||||
node.type = type;
|
||||
node.members = members && createNodeArray(members);
|
||||
node.transformFlags = TransformFlags.ContainsTypeScript;
|
||||
return node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode {
|
||||
function updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: readonly TypeElement[] | undefined): MappedTypeNode {
|
||||
return node.readonlyToken !== readonlyToken
|
||||
|| node.typeParameter !== typeParameter
|
||||
|| node.nameType !== nameType
|
||||
|| node.questionToken !== questionToken
|
||||
|| node.type !== type
|
||||
? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node)
|
||||
|| node.members !== members
|
||||
? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
@@ -3939,7 +3947,8 @@ namespace ts {
|
||||
decorators: readonly Decorator[] | undefined,
|
||||
modifiers: readonly Modifier[] | undefined,
|
||||
importClause: ImportClause | undefined,
|
||||
moduleSpecifier: Expression
|
||||
moduleSpecifier: Expression,
|
||||
assertClause: AssertClause | undefined
|
||||
): ImportDeclaration {
|
||||
const node = createBaseDeclaration<ImportDeclaration>(
|
||||
SyntaxKind.ImportDeclaration,
|
||||
@@ -3948,6 +3957,7 @@ namespace ts {
|
||||
);
|
||||
node.importClause = importClause;
|
||||
node.moduleSpecifier = moduleSpecifier;
|
||||
node.assertClause = assertClause;
|
||||
node.transformFlags |=
|
||||
propagateChildFlags(node.importClause) |
|
||||
propagateChildFlags(node.moduleSpecifier);
|
||||
@@ -3961,13 +3971,15 @@ namespace ts {
|
||||
decorators: readonly Decorator[] | undefined,
|
||||
modifiers: readonly Modifier[] | undefined,
|
||||
importClause: ImportClause | undefined,
|
||||
moduleSpecifier: Expression
|
||||
moduleSpecifier: Expression,
|
||||
assertClause: AssertClause | undefined
|
||||
) {
|
||||
return node.decorators !== decorators
|
||||
|| node.modifiers !== modifiers
|
||||
|| node.importClause !== importClause
|
||||
|| node.moduleSpecifier !== moduleSpecifier
|
||||
? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
|
||||
|| node.assertClause !== assertClause
|
||||
? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
@@ -3996,6 +4008,40 @@ namespace ts {
|
||||
: node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function createAssertClause(elements: readonly AssertEntry[], multiLine?: boolean): AssertClause {
|
||||
const node = createBaseNode<AssertClause>(SyntaxKind.AssertClause);
|
||||
node.elements = createNodeArray(elements);
|
||||
node.multiLine = multiLine;
|
||||
node.transformFlags |= TransformFlags.ContainsESNext;
|
||||
return node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function updateAssertClause(node: AssertClause, elements: readonly AssertEntry[], multiLine?: boolean): AssertClause {
|
||||
return node.elements !== elements
|
||||
|| node.multiLine !== multiLine
|
||||
? update(createAssertClause(elements, multiLine), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function createAssertEntry(name: AssertionKey, value: Expression): AssertEntry {
|
||||
const node = createBaseNode<AssertEntry>(SyntaxKind.AssertEntry);
|
||||
node.name = name;
|
||||
node.value = value;
|
||||
node.transformFlags |= TransformFlags.ContainsESNext;
|
||||
return node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry {
|
||||
return node.name !== name
|
||||
|| node.value !== value
|
||||
? update(createAssertEntry(name, value), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
// @api
|
||||
function createNamespaceImport(name: Identifier): NamespaceImport {
|
||||
const node = createBaseNode<NamespaceImport>(SyntaxKind.NamespaceImport);
|
||||
@@ -4047,8 +4093,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @api
|
||||
function createImportSpecifier(propertyName: Identifier | undefined, name: Identifier) {
|
||||
function createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) {
|
||||
const node = createBaseNode<ImportSpecifier>(SyntaxKind.ImportSpecifier);
|
||||
node.isTypeOnly = isTypeOnly;
|
||||
node.propertyName = propertyName;
|
||||
node.name = name;
|
||||
node.transformFlags |=
|
||||
@@ -4059,10 +4106,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @api
|
||||
function updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier) {
|
||||
return node.propertyName !== propertyName
|
||||
function updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) {
|
||||
return node.isTypeOnly !== isTypeOnly
|
||||
|| node.propertyName !== propertyName
|
||||
|| node.name !== name
|
||||
? update(createImportSpecifier(propertyName, name), node)
|
||||
? update(createImportSpecifier(isTypeOnly, propertyName, name), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
@@ -4107,7 +4155,8 @@ namespace ts {
|
||||
modifiers: readonly Modifier[] | undefined,
|
||||
isTypeOnly: boolean,
|
||||
exportClause: NamedExportBindings | undefined,
|
||||
moduleSpecifier?: Expression
|
||||
moduleSpecifier?: Expression,
|
||||
assertClause?: AssertClause
|
||||
) {
|
||||
const node = createBaseDeclaration<ExportDeclaration>(
|
||||
SyntaxKind.ExportDeclaration,
|
||||
@@ -4117,6 +4166,7 @@ namespace ts {
|
||||
node.isTypeOnly = isTypeOnly;
|
||||
node.exportClause = exportClause;
|
||||
node.moduleSpecifier = moduleSpecifier;
|
||||
node.assertClause = assertClause;
|
||||
node.transformFlags |=
|
||||
propagateChildFlags(node.exportClause) |
|
||||
propagateChildFlags(node.moduleSpecifier);
|
||||
@@ -4131,14 +4181,16 @@ namespace ts {
|
||||
modifiers: readonly Modifier[] | undefined,
|
||||
isTypeOnly: boolean,
|
||||
exportClause: NamedExportBindings | undefined,
|
||||
moduleSpecifier: Expression | undefined
|
||||
moduleSpecifier: Expression | undefined,
|
||||
assertClause: AssertClause | undefined
|
||||
) {
|
||||
return node.decorators !== decorators
|
||||
|| node.modifiers !== modifiers
|
||||
|| node.isTypeOnly !== isTypeOnly
|
||||
|| node.exportClause !== exportClause
|
||||
|| node.moduleSpecifier !== moduleSpecifier
|
||||
? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier), node)
|
||||
|| node.assertClause !== assertClause
|
||||
? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
@@ -4159,8 +4211,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @api
|
||||
function createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier) {
|
||||
function createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier) {
|
||||
const node = createBaseNode<ExportSpecifier>(SyntaxKind.ExportSpecifier);
|
||||
node.isTypeOnly = isTypeOnly;
|
||||
node.propertyName = asName(propertyName);
|
||||
node.name = asName(name);
|
||||
node.transformFlags |=
|
||||
@@ -4171,10 +4224,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
// @api
|
||||
function updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier) {
|
||||
return node.propertyName !== propertyName
|
||||
function updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier) {
|
||||
return node.isTypeOnly !== isTypeOnly
|
||||
|| node.propertyName !== propertyName
|
||||
|| node.name !== name
|
||||
? update(createExportSpecifier(propertyName, name), node)
|
||||
? update(createExportSpecifier(isTypeOnly, propertyName, name), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
@@ -5129,6 +5183,7 @@ namespace ts {
|
||||
node.transformFlags =
|
||||
propagateChildrenFlags(node.statements) |
|
||||
propagateChildFlags(node.endOfFileToken);
|
||||
node.impliedNodeFormat = source.impliedNodeFormat;
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -5441,7 +5496,7 @@ namespace ts {
|
||||
/*modifiers*/ undefined,
|
||||
/*isTypeOnly*/ false,
|
||||
createNamedExports([
|
||||
createExportSpecifier(/*propertyName*/ undefined, exportName)
|
||||
createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, exportName)
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -5832,7 +5887,7 @@ namespace ts {
|
||||
* @param visitor Optional callback used to visit any custom prologue directives.
|
||||
*/
|
||||
function copyPrologue(source: readonly Statement[], target: Push<Statement>, ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult<Node>): number {
|
||||
const offset = copyStandardPrologue(source, target, ensureUseStrict);
|
||||
const offset = copyStandardPrologue(source, target, 0, ensureUseStrict);
|
||||
return copyCustomPrologue(source, target, offset, visitor);
|
||||
}
|
||||
|
||||
@@ -5848,12 +5903,13 @@ namespace ts {
|
||||
* Copies only the standard (string-expression) prologue-directives into the target statement-array.
|
||||
* @param source origin statements array
|
||||
* @param target result statements array
|
||||
* @param statementOffset The offset at which to begin the copy.
|
||||
* @param ensureUseStrict boolean determining whether the function need to add prologue-directives
|
||||
* @returns Count of how many directive statements were copied.
|
||||
*/
|
||||
function copyStandardPrologue(source: readonly Statement[], target: Push<Statement>, ensureUseStrict?: boolean): number {
|
||||
function copyStandardPrologue(source: readonly Statement[], target: Push<Statement>, statementOffset = 0, ensureUseStrict?: boolean): number {
|
||||
Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
|
||||
let foundUseStrict = false;
|
||||
let statementOffset = 0;
|
||||
const numStatements = source.length;
|
||||
while (statementOffset < numStatements) {
|
||||
const statement = source[statementOffset];
|
||||
@@ -6027,32 +6083,36 @@ namespace ts {
|
||||
|
||||
function updateModifiers<T extends HasModifiers>(node: T, modifiers: readonly Modifier[] | ModifierFlags): T;
|
||||
function updateModifiers(node: HasModifiers, modifiers: readonly Modifier[] | ModifierFlags) {
|
||||
let modifierArray;
|
||||
if (typeof modifiers === "number") {
|
||||
modifiers = createModifiersFromModifierFlags(modifiers);
|
||||
modifierArray = createModifiersFromModifierFlags(modifiers);
|
||||
}
|
||||
return isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
|
||||
isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
|
||||
isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) :
|
||||
isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
|
||||
isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
|
||||
isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
|
||||
isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
|
||||
isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
|
||||
isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
|
||||
isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
|
||||
isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
|
||||
isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
|
||||
isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
|
||||
isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
|
||||
isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
|
||||
isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
|
||||
isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
|
||||
isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
|
||||
isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
|
||||
isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.name, node.moduleReference) :
|
||||
isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier) :
|
||||
isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
|
||||
isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier) :
|
||||
else {
|
||||
modifierArray = modifiers;
|
||||
}
|
||||
return isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifierArray, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
|
||||
isPropertySignature(node) ? updatePropertySignature(node, modifierArray, node.name, node.questionToken, node.type) :
|
||||
isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifierArray, node.name, node.questionToken ?? node.exclamationToken, node.type, node.initializer) :
|
||||
isMethodSignature(node) ? updateMethodSignature(node, modifierArray, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
|
||||
isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
|
||||
isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifierArray, node.parameters, node.body) :
|
||||
isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.type, node.body) :
|
||||
isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifierArray, node.name, node.parameters, node.body) :
|
||||
isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifierArray, node.parameters, node.type) :
|
||||
isFunctionExpression(node) ? updateFunctionExpression(node, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
|
||||
isArrowFunction(node) ? updateArrowFunction(node, modifierArray, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
|
||||
isClassExpression(node) ? updateClassExpression(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) :
|
||||
isVariableStatement(node) ? updateVariableStatement(node, modifierArray, node.declarationList) :
|
||||
isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifierArray, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
|
||||
isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) :
|
||||
isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.heritageClauses, node.members) :
|
||||
isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifierArray, node.name, node.typeParameters, node.type) :
|
||||
isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifierArray, node.name, node.members) :
|
||||
isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifierArray, node.name, node.body) :
|
||||
isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.name, node.moduleReference) :
|
||||
isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifierArray, node.importClause, node.moduleSpecifier, node.assertClause) :
|
||||
isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifierArray, node.expression) :
|
||||
isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifierArray, node.isTypeOnly, node.exportClause, node.moduleSpecifier, node.assertClause) :
|
||||
Debug.assertNever(node);
|
||||
}
|
||||
|
||||
@@ -6334,7 +6394,7 @@ namespace ts {
|
||||
sourceMapText = mapTextOrStripInternal as string;
|
||||
}
|
||||
const node = oldFileOfCurrentEmit ?
|
||||
parseOldFileOfCurrentEmit(Debug.assertDefined(bundleFileInfo)) :
|
||||
parseOldFileOfCurrentEmit(Debug.checkDefined(bundleFileInfo)) :
|
||||
parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
|
||||
node.fileName = fileName;
|
||||
node.sourceMapPath = sourceMapPath;
|
||||
@@ -6356,7 +6416,7 @@ namespace ts {
|
||||
let prologues: UnparsedPrologue[] | undefined;
|
||||
let helpers: UnscopedEmitHelper[] | undefined;
|
||||
let referencedFiles: FileReference[] | undefined;
|
||||
let typeReferenceDirectives: string[] | undefined;
|
||||
let typeReferenceDirectives: FileReference[] | undefined;
|
||||
let libReferenceDirectives: FileReference[] | undefined;
|
||||
let prependChildren: UnparsedTextLike[] | undefined;
|
||||
let texts: UnparsedSourceText[] | undefined;
|
||||
@@ -6377,7 +6437,13 @@ namespace ts {
|
||||
referencedFiles = append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
|
||||
break;
|
||||
case BundleFileSectionKind.Type:
|
||||
typeReferenceDirectives = append(typeReferenceDirectives, section.data);
|
||||
typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
|
||||
break;
|
||||
case BundleFileSectionKind.TypeResolutionModeImport:
|
||||
typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: ModuleKind.ESNext });
|
||||
break;
|
||||
case BundleFileSectionKind.TypeResolutionModeRequire:
|
||||
typeReferenceDirectives = append(typeReferenceDirectives, { pos: -1, end: -1, fileName: section.data, resolutionMode: ModuleKind.CommonJS });
|
||||
break;
|
||||
case BundleFileSectionKind.Lib:
|
||||
libReferenceDirectives = append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
|
||||
@@ -6438,6 +6504,8 @@ namespace ts {
|
||||
case BundleFileSectionKind.NoDefaultLib:
|
||||
case BundleFileSectionKind.Reference:
|
||||
case BundleFileSectionKind.Type:
|
||||
case BundleFileSectionKind.TypeResolutionModeImport:
|
||||
case BundleFileSectionKind.TypeResolutionModeRequire:
|
||||
case BundleFileSectionKind.Lib:
|
||||
syntheticReferences = append(syntheticReferences, setTextRange(factory.createUnparsedSyntheticReference(section), section));
|
||||
break;
|
||||
@@ -6534,13 +6602,13 @@ namespace ts {
|
||||
};
|
||||
node.javascriptPath = declarationTextOrJavascriptPath;
|
||||
node.javascriptMapPath = javascriptMapPath;
|
||||
node.declarationPath = Debug.assertDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationPath = Debug.checkDefined(javascriptMapTextOrDeclarationPath);
|
||||
node.declarationMapPath = declarationMapPath;
|
||||
node.buildInfoPath = declarationMapTextOrBuildInfoPath;
|
||||
Object.defineProperties(node, {
|
||||
javascriptText: { get() { return definedTextGetter(declarationTextOrJavascriptPath); } },
|
||||
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
|
||||
buildInfo: { get() { return getAndCacheBuildInfo(() => textGetter(declarationMapTextOrBuildInfoPath)); } }
|
||||
});
|
||||
|
||||
@@ -597,6 +597,14 @@ namespace ts {
|
||||
return node.kind === SyntaxKind.ImportClause;
|
||||
}
|
||||
|
||||
export function isAssertClause(node: Node): node is AssertClause {
|
||||
return node.kind === SyntaxKind.AssertClause;
|
||||
}
|
||||
|
||||
export function isAssertEntry(node: Node): node is AssertEntry {
|
||||
return node.kind === SyntaxKind.AssertEntry;
|
||||
}
|
||||
|
||||
export function isNamespaceImport(node: Node): node is NamespaceImport {
|
||||
return node.kind === SyntaxKind.NamespaceImport;
|
||||
}
|
||||
|
||||
@@ -452,4 +452,4 @@ namespace ts {
|
||||
parenthesizeConstituentTypesOfUnionOrIntersectionType: nodes => cast(nodes, isNodeArray),
|
||||
parenthesizeTypeArguments: nodes => nodes && cast(nodes, isNodeArray),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,7 +481,7 @@ namespace ts {
|
||||
if (compilerOptions.importHelpers && isEffectiveExternalModule(sourceFile, compilerOptions)) {
|
||||
let namedBindings: NamedImportBindings | undefined;
|
||||
const moduleKind = getEmitModuleKind(compilerOptions);
|
||||
if (moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext) {
|
||||
if ((moduleKind >= ModuleKind.ES2015 && moduleKind <= ModuleKind.ESNext) || sourceFile.impliedNodeFormat === ModuleKind.ESNext) {
|
||||
// use named imports
|
||||
const helpers = getEmitHelpers(sourceFile);
|
||||
if (helpers) {
|
||||
@@ -500,8 +500,8 @@ namespace ts {
|
||||
// NOTE: We don't need to care about global import collisions as this is a module.
|
||||
namedBindings = nodeFactory.createNamedImports(
|
||||
map(helperNames, name => isFileLevelUniqueName(sourceFile, name)
|
||||
? nodeFactory.createImportSpecifier(/*propertyName*/ undefined, nodeFactory.createIdentifier(name))
|
||||
: nodeFactory.createImportSpecifier(nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name))
|
||||
? nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, nodeFactory.createIdentifier(name))
|
||||
: nodeFactory.createImportSpecifier(/*isTypeOnly*/ false, nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name))
|
||||
)
|
||||
);
|
||||
const parseNode = getOriginalNode(sourceFile, isSourceFile);
|
||||
@@ -522,7 +522,8 @@ namespace ts {
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings),
|
||||
nodeFactory.createStringLiteral(externalHelpersModuleNameText)
|
||||
nodeFactory.createStringLiteral(externalHelpersModuleNameText),
|
||||
/*assertClause*/ undefined
|
||||
);
|
||||
addEmitFlags(externalHelpersImportDeclaration, EmitFlags.NeverApplyImportHelper);
|
||||
return externalHelpersImportDeclaration;
|
||||
@@ -538,9 +539,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
const moduleKind = getEmitModuleKind(compilerOptions);
|
||||
let create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
|
||||
let create = (hasExportStarsToExportValues || (getESModuleInterop(compilerOptions) && hasImportStarOrImportDefault))
|
||||
&& moduleKind !== ModuleKind.System
|
||||
&& moduleKind < ModuleKind.ES2015;
|
||||
&& (moduleKind < ModuleKind.ES2015 || node.impliedNodeFormat === ModuleKind.CommonJS);
|
||||
if (!create) {
|
||||
const helpers = getEmitHelpers(node);
|
||||
if (helpers) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -11,7 +11,7 @@ namespace ts.moduleSpecifiers {
|
||||
readonly ending: Ending;
|
||||
}
|
||||
|
||||
function getPreferences({ importModuleSpecifierPreference, importModuleSpecifierEnding }: UserPreferences, compilerOptions: CompilerOptions, importingSourceFile: SourceFile): Preferences {
|
||||
function getPreferences(host: ModuleSpecifierResolutionHost, { importModuleSpecifierPreference, importModuleSpecifierEnding }: UserPreferences, compilerOptions: CompilerOptions, importingSourceFile: SourceFile): Preferences {
|
||||
return {
|
||||
relativePreference:
|
||||
importModuleSpecifierPreference === "relative" ? RelativePreference.Relative :
|
||||
@@ -25,34 +25,63 @@ namespace ts.moduleSpecifiers {
|
||||
case "minimal": return Ending.Minimal;
|
||||
case "index": return Ending.Index;
|
||||
case "js": return Ending.JsExtension;
|
||||
default: return usesJsExtensionOnImports(importingSourceFile) ? Ending.JsExtension
|
||||
default: return usesJsExtensionOnImports(importingSourceFile) || isFormatRequiringExtensions(compilerOptions, importingSourceFile.path, host) ? Ending.JsExtension
|
||||
: getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs ? Ending.Index : Ending.Minimal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string): Preferences {
|
||||
function getPreferencesForUpdate(compilerOptions: CompilerOptions, oldImportSpecifier: string, importingSourceFileName: Path, host: ModuleSpecifierResolutionHost): Preferences {
|
||||
return {
|
||||
relativePreference: isExternalModuleNameRelative(oldImportSpecifier) ? RelativePreference.Relative : RelativePreference.NonRelative,
|
||||
ending: hasJSFileExtension(oldImportSpecifier) ?
|
||||
ending: hasJSFileExtension(oldImportSpecifier) || isFormatRequiringExtensions(compilerOptions, importingSourceFileName, host) ?
|
||||
Ending.JsExtension :
|
||||
getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeJs || endsWith(oldImportSpecifier, "index") ? Ending.Index : Ending.Minimal,
|
||||
};
|
||||
}
|
||||
|
||||
function isFormatRequiringExtensions(compilerOptions: CompilerOptions, importingSourceFileName: Path, host: ModuleSpecifierResolutionHost) {
|
||||
if (getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Node12
|
||||
&& getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.NodeNext) {
|
||||
return false;
|
||||
}
|
||||
return getImpliedNodeFormatForFile(importingSourceFileName, host.getPackageJsonInfoCache?.(), getModuleResolutionHost(host), compilerOptions) !== ModuleKind.CommonJS;
|
||||
}
|
||||
|
||||
function getModuleResolutionHost(host: ModuleSpecifierResolutionHost): ModuleResolutionHost {
|
||||
return {
|
||||
fileExists: host.fileExists,
|
||||
readFile: Debug.checkDefined(host.readFile),
|
||||
directoryExists: host.directoryExists,
|
||||
getCurrentDirectory: host.getCurrentDirectory,
|
||||
realpath: host.realpath,
|
||||
useCaseSensitiveFileNames: host.useCaseSensitiveFileNames?.(),
|
||||
};
|
||||
}
|
||||
|
||||
// `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`?
|
||||
// Because when this is called by the file renamer, `importingSourceFile` is the file being renamed,
|
||||
// while `importingSourceFileName` its *new* name. We need a source file just to get its
|
||||
// `impliedNodeFormat` and to detect certain preferences from existing import module specifiers.
|
||||
export function updateModuleSpecifier(
|
||||
compilerOptions: CompilerOptions,
|
||||
importingSourceFile: SourceFile,
|
||||
importingSourceFileName: Path,
|
||||
toFileName: string,
|
||||
host: ModuleSpecifierResolutionHost,
|
||||
oldImportSpecifier: string,
|
||||
): string | undefined {
|
||||
const res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier), {});
|
||||
const res = getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier, importingSourceFileName, host), {});
|
||||
if (res === oldImportSpecifier) return undefined;
|
||||
return res;
|
||||
}
|
||||
|
||||
// Note: importingSourceFile is just for usesJsExtensionOnImports
|
||||
// `importingSourceFile` and `importingSourceFileName`? Why not just use `importingSourceFile.path`?
|
||||
// Because when this is called by the declaration emitter, `importingSourceFile` is the implementation
|
||||
// file, but `importingSourceFileName` and `toFileName` refer to declaration files (the former to the
|
||||
// one currently being produced; the latter to the one being imported). We need an implementation file
|
||||
// just to get its `impliedNodeFormat` and to detect certain preferences from existing import module
|
||||
// specifiers.
|
||||
export function getModuleSpecifier(
|
||||
compilerOptions: CompilerOptions,
|
||||
importingSourceFile: SourceFile,
|
||||
@@ -60,24 +89,25 @@ namespace ts.moduleSpecifiers {
|
||||
toFileName: string,
|
||||
host: ModuleSpecifierResolutionHost,
|
||||
): string {
|
||||
return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences({}, compilerOptions, importingSourceFile), {});
|
||||
return getModuleSpecifierWorker(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, getPreferences(host, {}, compilerOptions, importingSourceFile), {});
|
||||
}
|
||||
|
||||
export function getNodeModulesPackageName(
|
||||
compilerOptions: CompilerOptions,
|
||||
importingSourceFileName: Path,
|
||||
importingSourceFile: SourceFile,
|
||||
nodeModulesFileName: string,
|
||||
host: ModuleSpecifierResolutionHost,
|
||||
preferences: UserPreferences,
|
||||
): string | undefined {
|
||||
const info = getInfo(importingSourceFileName, host);
|
||||
const modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host, preferences);
|
||||
const info = getInfo(importingSourceFile.path, host);
|
||||
const modulePaths = getAllModulePaths(importingSourceFile.path, nodeModulesFileName, host, preferences);
|
||||
return firstDefined(modulePaths,
|
||||
modulePath => tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true));
|
||||
modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions, /*packageNameOnly*/ true));
|
||||
}
|
||||
|
||||
function getModuleSpecifierWorker(
|
||||
compilerOptions: CompilerOptions,
|
||||
importingSourceFile: SourceFile,
|
||||
importingSourceFileName: Path,
|
||||
toFileName: string,
|
||||
host: ModuleSpecifierResolutionHost,
|
||||
@@ -86,7 +116,7 @@ namespace ts.moduleSpecifiers {
|
||||
): string {
|
||||
const info = getInfo(importingSourceFileName, host);
|
||||
const modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host, userPreferences);
|
||||
return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions)) ||
|
||||
return firstDefined(modulePaths, modulePath => tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions)) ||
|
||||
getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences);
|
||||
}
|
||||
|
||||
@@ -175,7 +205,7 @@ namespace ts.moduleSpecifiers {
|
||||
userPreferences: UserPreferences,
|
||||
): readonly string[] {
|
||||
const info = getInfo(importingSourceFile.path, host);
|
||||
const preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
|
||||
const preferences = getPreferences(host, userPreferences, compilerOptions, importingSourceFile);
|
||||
const existingSpecifier = forEach(modulePaths, modulePath => forEach(
|
||||
host.getFileIncludeReasons().get(toPath(modulePath.path, host.getCurrentDirectory(), info.getCanonicalFileName)),
|
||||
reason => {
|
||||
@@ -203,7 +233,7 @@ namespace ts.moduleSpecifiers {
|
||||
let pathsSpecifiers: string[] | undefined;
|
||||
let relativeSpecifiers: string[] | undefined;
|
||||
for (const modulePath of modulePaths) {
|
||||
const specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions);
|
||||
const specifier = tryGetModuleNameAsNodeModule(modulePath, info, importingSourceFile, host, compilerOptions);
|
||||
nodeModulesSpecifiers = append(nodeModulesSpecifiers, specifier);
|
||||
if (specifier && modulePath.isRedirect) {
|
||||
// If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
|
||||
@@ -536,6 +566,77 @@ namespace ts.moduleSpecifiers {
|
||||
}
|
||||
}
|
||||
|
||||
const enum MatchingMode {
|
||||
Exact,
|
||||
Directory,
|
||||
Pattern
|
||||
}
|
||||
|
||||
function tryGetModuleNameFromExports(options: CompilerOptions, targetFilePath: string, packageDirectory: string, packageName: string, exports: unknown, conditions: string[], mode = MatchingMode.Exact): { moduleFileToTry: string } | undefined {
|
||||
if (typeof exports === "string") {
|
||||
const pathOrPattern = getNormalizedAbsolutePath(combinePaths(packageDirectory, exports), /*currentDirectory*/ undefined);
|
||||
const extensionSwappedTarget = hasTSFileExtension(targetFilePath) ? removeFileExtension(targetFilePath) + tryGetJSExtensionForFile(targetFilePath, options) : undefined;
|
||||
switch (mode) {
|
||||
case MatchingMode.Exact:
|
||||
if (comparePaths(targetFilePath, pathOrPattern) === Comparison.EqualTo || (extensionSwappedTarget && comparePaths(extensionSwappedTarget, pathOrPattern) === Comparison.EqualTo)) {
|
||||
return { moduleFileToTry: packageName };
|
||||
}
|
||||
break;
|
||||
case MatchingMode.Directory:
|
||||
if (containsPath(pathOrPattern, targetFilePath)) {
|
||||
const fragment = getRelativePathFromDirectory(pathOrPattern, targetFilePath, /*ignoreCase*/ false);
|
||||
return { moduleFileToTry: getNormalizedAbsolutePath(combinePaths(combinePaths(packageName, exports), fragment), /*currentDirectory*/ undefined) };
|
||||
}
|
||||
break;
|
||||
case MatchingMode.Pattern:
|
||||
const starPos = pathOrPattern.indexOf("*");
|
||||
const leadingSlice = pathOrPattern.slice(0, starPos);
|
||||
const trailingSlice = pathOrPattern.slice(starPos + 1);
|
||||
if (startsWith(targetFilePath, leadingSlice) && endsWith(targetFilePath, trailingSlice)) {
|
||||
const starReplacement = targetFilePath.slice(leadingSlice.length, targetFilePath.length - trailingSlice.length);
|
||||
return { moduleFileToTry: packageName.replace("*", starReplacement) };
|
||||
}
|
||||
if (extensionSwappedTarget && startsWith(extensionSwappedTarget, leadingSlice) && endsWith(extensionSwappedTarget, trailingSlice)) {
|
||||
const starReplacement = extensionSwappedTarget.slice(leadingSlice.length, extensionSwappedTarget.length - trailingSlice.length);
|
||||
return { moduleFileToTry: packageName.replace("*", starReplacement) };
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (Array.isArray(exports)) {
|
||||
return forEach(exports, e => tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, e, conditions));
|
||||
}
|
||||
else if (typeof exports === "object" && exports !== null) { // eslint-disable-line no-null/no-null
|
||||
if (allKeysStartWithDot(exports as MapLike<unknown>)) {
|
||||
// sub-mappings
|
||||
// 3 cases:
|
||||
// * directory mappings (legacyish, key ends with / (technically allows index/extension resolution under cjs mode))
|
||||
// * pattern mappings (contains a *)
|
||||
// * exact mappings (no *, does not end with /)
|
||||
return forEach(getOwnKeys(exports as MapLike<unknown>), k => {
|
||||
const subPackageName = getNormalizedAbsolutePath(combinePaths(packageName, k), /*currentDirectory*/ undefined);
|
||||
const mode = endsWith(k, "/") ? MatchingMode.Directory
|
||||
: stringContains(k, "*") ? MatchingMode.Pattern
|
||||
: MatchingMode.Exact;
|
||||
return tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, subPackageName, (exports as MapLike<unknown>)[k], conditions, mode);
|
||||
});
|
||||
}
|
||||
else {
|
||||
// conditional mapping
|
||||
for (const key of getOwnKeys(exports as MapLike<unknown>)) {
|
||||
if (key === "default" || conditions.indexOf(key) >= 0 || isApplicableVersionedTypesKey(conditions, key)) {
|
||||
const subTarget = (exports as MapLike<unknown>)[key];
|
||||
const result = tryGetModuleNameFromExports(options, targetFilePath, packageDirectory, packageName, subTarget, conditions);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function tryGetModuleNameFromRootDirs(rootDirs: readonly string[], moduleFileName: string, sourceDirectory: string, getCanonicalFileName: (file: string) => string, ending: Ending, compilerOptions: CompilerOptions): string | undefined {
|
||||
const normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
|
||||
if (normalizedTargetPath === undefined) {
|
||||
@@ -549,7 +650,7 @@ namespace ts.moduleSpecifiers {
|
||||
: removeFileExtension(relativePath);
|
||||
}
|
||||
|
||||
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, host: ModuleSpecifierResolutionHost, options: CompilerOptions, packageNameOnly?: boolean): string | undefined {
|
||||
function tryGetModuleNameAsNodeModule({ path, isRedirect }: ModulePath, { getCanonicalFileName, sourceDirectory }: Info, importingSourceFile: SourceFile , host: ModuleSpecifierResolutionHost, options: CompilerOptions, packageNameOnly?: boolean): string | undefined {
|
||||
if (!host.fileExists || !host.readFile) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -567,7 +668,15 @@ namespace ts.moduleSpecifiers {
|
||||
let moduleFileNameForExtensionless: string | undefined;
|
||||
while (true) {
|
||||
// If the module could be imported by a directory name, use that directory's name
|
||||
const { moduleFileToTry, packageRootPath } = tryDirectoryWithPackageJson(packageRootIndex);
|
||||
const { moduleFileToTry, packageRootPath, blockedByExports, verbatimFromExports } = tryDirectoryWithPackageJson(packageRootIndex);
|
||||
if (getEmitModuleResolutionKind(options) !== ModuleResolutionKind.Classic) {
|
||||
if (blockedByExports) {
|
||||
return undefined; // File is under this package.json, but is not publicly exported - there's no way to name it via `node_modules` resolution
|
||||
}
|
||||
if (verbatimFromExports) {
|
||||
return moduleFileToTry;
|
||||
}
|
||||
}
|
||||
if (packageRootPath) {
|
||||
moduleSpecifier = packageRootPath;
|
||||
isPackageRootPath = true;
|
||||
@@ -600,14 +709,34 @@ namespace ts.moduleSpecifiers {
|
||||
const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
|
||||
const packageName = getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
|
||||
// For classic resolution, only allow importing from node_modules/@types, not other node_modules
|
||||
return getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
|
||||
return getEmitModuleResolutionKind(options) === ModuleResolutionKind.Classic && packageName === nodeModulesDirectoryName ? undefined : packageName;
|
||||
|
||||
function tryDirectoryWithPackageJson(packageRootIndex: number) {
|
||||
function tryDirectoryWithPackageJson(packageRootIndex: number): { moduleFileToTry: string, packageRootPath?: string, blockedByExports?: true, verbatimFromExports?: true } {
|
||||
const packageRootPath = path.substring(0, packageRootIndex);
|
||||
const packageJsonPath = combinePaths(packageRootPath, "package.json");
|
||||
let moduleFileToTry = path;
|
||||
if (host.fileExists(packageJsonPath)) {
|
||||
const packageJsonContent = JSON.parse(host.readFile!(packageJsonPath)!);
|
||||
const cachedPackageJson = host.getPackageJsonInfoCache?.()?.getPackageJsonInfo(packageJsonPath);
|
||||
if (typeof cachedPackageJson === "object" || cachedPackageJson === undefined && host.fileExists(packageJsonPath)) {
|
||||
const packageJsonContent = cachedPackageJson?.packageJsonContent || JSON.parse(host.readFile!(packageJsonPath)!);
|
||||
if (getEmitModuleResolutionKind(options) === ModuleResolutionKind.Node12 || getEmitModuleResolutionKind(options) === ModuleResolutionKind.NodeNext) {
|
||||
// `conditions` *could* be made to go against `importingSourceFile.impliedNodeFormat` if something wanted to generate
|
||||
// an ImportEqualsDeclaration in an ESM-implied file or an ImportCall in a CJS-implied file. But since this function is
|
||||
// usually called to conjure an import out of thin air, we don't have an existing usage to call `getModeForUsageAtIndex`
|
||||
// with, so for now we just stick with the mode of the file.
|
||||
const conditions = ["node", importingSourceFile.impliedNodeFormat === ModuleKind.ESNext ? "import" : "require", "types"];
|
||||
const fromExports = packageJsonContent.exports && typeof packageJsonContent.name === "string"
|
||||
? tryGetModuleNameFromExports(options, path, packageRootPath, getPackageNameFromTypesPackageName(packageJsonContent.name), packageJsonContent.exports, conditions)
|
||||
: undefined;
|
||||
if (fromExports) {
|
||||
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 };
|
||||
}
|
||||
}
|
||||
const versionPaths = packageJsonContent.typesVersions
|
||||
? getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
|
||||
: undefined;
|
||||
@@ -622,7 +751,6 @@ namespace ts.moduleSpecifiers {
|
||||
moduleFileToTry = combinePaths(packageRootPath, fromPaths);
|
||||
}
|
||||
}
|
||||
|
||||
// If the file is the main module, it can be imported by the package name
|
||||
const mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
|
||||
if (isString(mainFileRelative)) {
|
||||
@@ -652,7 +780,7 @@ namespace ts.moduleSpecifiers {
|
||||
function tryGetAnyFileFromPath(host: ModuleSpecifierResolutionHost, path: string) {
|
||||
if (!host.fileExists) return;
|
||||
// We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
|
||||
const extensions = getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ScriptKind.JSON }]);
|
||||
const extensions = flatten(getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: ScriptKind.JSON }]));
|
||||
for (const e of extensions) {
|
||||
const fullPath = path + e;
|
||||
if (host.fileExists(fullPath)) {
|
||||
@@ -661,80 +789,17 @@ namespace ts.moduleSpecifiers {
|
||||
}
|
||||
}
|
||||
|
||||
interface NodeModulePathParts {
|
||||
readonly topLevelNodeModulesIndex: number;
|
||||
readonly topLevelPackageNameIndex: number;
|
||||
readonly packageRootIndex: number;
|
||||
readonly fileNameIndex: number;
|
||||
}
|
||||
function getNodeModulePathParts(fullPath: string): NodeModulePathParts | undefined {
|
||||
// If fullPath can't be valid module file within node_modules, returns undefined.
|
||||
// Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
|
||||
// Returns indices: ^ ^ ^ ^
|
||||
|
||||
let topLevelNodeModulesIndex = 0;
|
||||
let topLevelPackageNameIndex = 0;
|
||||
let packageRootIndex = 0;
|
||||
let fileNameIndex = 0;
|
||||
|
||||
const enum States {
|
||||
BeforeNodeModules,
|
||||
NodeModules,
|
||||
Scope,
|
||||
PackageContent
|
||||
}
|
||||
|
||||
let partStart = 0;
|
||||
let partEnd = 0;
|
||||
let state = States.BeforeNodeModules;
|
||||
|
||||
while (partEnd >= 0) {
|
||||
partStart = partEnd;
|
||||
partEnd = fullPath.indexOf("/", partStart + 1);
|
||||
switch (state) {
|
||||
case States.BeforeNodeModules:
|
||||
if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
|
||||
topLevelNodeModulesIndex = partStart;
|
||||
topLevelPackageNameIndex = partEnd;
|
||||
state = States.NodeModules;
|
||||
}
|
||||
break;
|
||||
case States.NodeModules:
|
||||
case States.Scope:
|
||||
if (state === States.NodeModules && fullPath.charAt(partStart + 1) === "@") {
|
||||
state = States.Scope;
|
||||
}
|
||||
else {
|
||||
packageRootIndex = partEnd;
|
||||
state = States.PackageContent;
|
||||
}
|
||||
break;
|
||||
case States.PackageContent:
|
||||
if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
|
||||
state = States.NodeModules;
|
||||
}
|
||||
else {
|
||||
state = States.PackageContent;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fileNameIndex = partStart;
|
||||
|
||||
return state > States.NodeModules ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : undefined;
|
||||
}
|
||||
|
||||
function getPathRelativeToRootDirs(path: string, rootDirs: readonly string[], getCanonicalFileName: GetCanonicalFileName): string | undefined {
|
||||
return firstDefined(rootDirs, rootDir => {
|
||||
const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName)!; // TODO: GH#18217
|
||||
return isPathRelativeToParent(relativePath) ? undefined : relativePath;
|
||||
const relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName);
|
||||
return relativePath !== undefined && isPathRelativeToParent(relativePath) ? undefined : relativePath;
|
||||
});
|
||||
}
|
||||
|
||||
function removeExtensionAndIndexPostFix(fileName: string, ending: Ending, options: CompilerOptions): string {
|
||||
if (fileExtensionIs(fileName, Extension.Json)) return fileName;
|
||||
if (fileExtensionIsOneOf(fileName, [Extension.Json, Extension.Mjs, Extension.Cjs])) return fileName;
|
||||
const noExtension = removeFileExtension(fileName);
|
||||
if (fileExtensionIsOneOf(fileName, [Extension.Dmts, Extension.Mts, Extension.Dcts, Extension.Cts])) return noExtension + getJSExtensionForFile(fileName, options);
|
||||
switch (ending) {
|
||||
case Ending.Minimal:
|
||||
return removeSuffix(noExtension, "/index");
|
||||
@@ -763,6 +828,14 @@ namespace ts.moduleSpecifiers {
|
||||
case Extension.Jsx:
|
||||
case Extension.Json:
|
||||
return ext;
|
||||
case Extension.Dmts:
|
||||
case Extension.Mts:
|
||||
case Extension.Mjs:
|
||||
return Extension.Mjs;
|
||||
case Extension.Dcts:
|
||||
case Extension.Cts:
|
||||
case Extension.Cjs:
|
||||
return Extension.Cjs;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
+254
-125
@@ -180,7 +180,8 @@ namespace ts {
|
||||
visitNode(cbNode, (node as TypePredicateNode).parameterName) ||
|
||||
visitNode(cbNode, (node as TypePredicateNode).type);
|
||||
case SyntaxKind.TypeQuery:
|
||||
return visitNode(cbNode, (node as TypeQueryNode).exprName);
|
||||
return visitNode(cbNode, (node as TypeQueryNode).exprName) ||
|
||||
visitNodes(cbNode, cbNodes, (node as TypeQueryNode).typeArguments);
|
||||
case SyntaxKind.TypeLiteral:
|
||||
return visitNodes(cbNode, cbNodes, (node as TypeLiteralNode).members);
|
||||
case SyntaxKind.ArrayType:
|
||||
@@ -212,7 +213,8 @@ namespace ts {
|
||||
visitNode(cbNode, (node as MappedTypeNode).typeParameter) ||
|
||||
visitNode(cbNode, (node as MappedTypeNode).nameType) ||
|
||||
visitNode(cbNode, (node as MappedTypeNode).questionToken) ||
|
||||
visitNode(cbNode, (node as MappedTypeNode).type);
|
||||
visitNode(cbNode, (node as MappedTypeNode).type) ||
|
||||
visitNodes(cbNode, cbNodes, (node as MappedTypeNode).members);
|
||||
case SyntaxKind.LiteralType:
|
||||
return visitNode(cbNode, (node as LiteralTypeNode).literal);
|
||||
case SyntaxKind.NamedTupleMember:
|
||||
@@ -398,13 +400,18 @@ namespace ts {
|
||||
return visitNodes(cbNode, cbNodes, node.decorators) ||
|
||||
visitNodes(cbNode, cbNodes, node.modifiers) ||
|
||||
visitNode(cbNode, (node as ImportDeclaration).importClause) ||
|
||||
visitNode(cbNode, (node as ImportDeclaration).moduleSpecifier);
|
||||
visitNode(cbNode, (node as ImportDeclaration).moduleSpecifier) ||
|
||||
visitNode(cbNode, (node as ImportDeclaration).assertClause);
|
||||
case SyntaxKind.ImportClause:
|
||||
return visitNode(cbNode, (node as ImportClause).name) ||
|
||||
visitNode(cbNode, (node as ImportClause).namedBindings);
|
||||
case SyntaxKind.AssertClause:
|
||||
return visitNodes(cbNode, cbNodes, (node as AssertClause).elements);
|
||||
case SyntaxKind.AssertEntry:
|
||||
return visitNode(cbNode, (node as AssertEntry).name) ||
|
||||
visitNode(cbNode, (node as AssertEntry).value);
|
||||
case SyntaxKind.NamespaceExportDeclaration:
|
||||
return visitNode(cbNode, (node as NamespaceExportDeclaration).name);
|
||||
|
||||
case SyntaxKind.NamespaceImport:
|
||||
return visitNode(cbNode, (node as NamespaceImport).name);
|
||||
case SyntaxKind.NamespaceExport:
|
||||
@@ -416,7 +423,8 @@ namespace ts {
|
||||
return visitNodes(cbNode, cbNodes, node.decorators) ||
|
||||
visitNodes(cbNode, cbNodes, node.modifiers) ||
|
||||
visitNode(cbNode, (node as ExportDeclaration).exportClause) ||
|
||||
visitNode(cbNode, (node as ExportDeclaration).moduleSpecifier);
|
||||
visitNode(cbNode, (node as ExportDeclaration).moduleSpecifier) ||
|
||||
visitNode(cbNode, (node as ExportDeclaration).assertClause);
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
case SyntaxKind.ExportSpecifier:
|
||||
return visitNode(cbNode, (node as ImportOrExportSpecifier).propertyName) ||
|
||||
@@ -868,7 +876,7 @@ namespace ts {
|
||||
initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, ScriptKind.JS);
|
||||
// Prime the scanner.
|
||||
nextToken();
|
||||
const entityName = parseEntityName(/*allowReservedWords*/ true);
|
||||
const entityName = parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ false);
|
||||
const isInvalid = token() === SyntaxKind.EndOfFileToken && !parseDiagnostics.length;
|
||||
clearState();
|
||||
return isInvalid ? entityName : undefined;
|
||||
@@ -1633,7 +1641,7 @@ namespace ts {
|
||||
parseErrorAtCurrentToken(blankDiagnostic);
|
||||
}
|
||||
else {
|
||||
parseErrorAtCurrentToken(nameDiagnostic, tokenToString(token()));
|
||||
parseErrorAtCurrentToken(nameDiagnostic, scanner.getTokenValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1886,6 +1894,11 @@ namespace ts {
|
||||
token() === SyntaxKind.NumericLiteral;
|
||||
}
|
||||
|
||||
function isAssertionKey(): boolean {
|
||||
return tokenIsIdentifierOrKeyword(token()) ||
|
||||
token() === SyntaxKind.StringLiteral;
|
||||
}
|
||||
|
||||
function parsePropertyNameWorker(allowComputedPropertyNames: boolean): PropertyName {
|
||||
if (token() === SyntaxKind.StringLiteral || token() === SyntaxKind.NumericLiteral) {
|
||||
const node = parseLiteralNode() as StringLiteral | NumericLiteral;
|
||||
@@ -1963,7 +1976,6 @@ namespace ts {
|
||||
case SyntaxKind.DefaultKeyword:
|
||||
return nextTokenCanFollowDefaultKeyword();
|
||||
case SyntaxKind.StaticKeyword:
|
||||
return nextTokenIsOnSameLineAndCanFollowModifier();
|
||||
case SyntaxKind.GetKeyword:
|
||||
case SyntaxKind.SetKeyword:
|
||||
nextToken();
|
||||
@@ -2051,6 +2063,8 @@ namespace ts {
|
||||
return isLiteralPropertyName();
|
||||
case ParsingContext.ObjectBindingElements:
|
||||
return token() === SyntaxKind.OpenBracketToken || token() === SyntaxKind.DotDotDotToken || isLiteralPropertyName();
|
||||
case ParsingContext.AssertEntries:
|
||||
return isAssertionKey();
|
||||
case ParsingContext.HeritageClauseElement:
|
||||
// If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
|
||||
// That way we won't consume the body of a class in its heritage clause.
|
||||
@@ -2171,6 +2185,7 @@ namespace ts {
|
||||
case ParsingContext.ObjectLiteralMembers:
|
||||
case ParsingContext.ObjectBindingElements:
|
||||
case ParsingContext.ImportOrExportSpecifiers:
|
||||
case ParsingContext.AssertEntries:
|
||||
return token() === SyntaxKind.CloseBraceToken;
|
||||
case ParsingContext.SwitchClauseStatements:
|
||||
return token() === SyntaxKind.CloseBraceToken || token() === SyntaxKind.CaseKeyword || token() === SyntaxKind.DefaultKeyword;
|
||||
@@ -2597,7 +2612,10 @@ namespace ts {
|
||||
case ParsingContext.ObjectLiteralMembers: return parseErrorAtCurrentToken(Diagnostics.Property_assignment_expected);
|
||||
case ParsingContext.ArrayLiteralMembers: return parseErrorAtCurrentToken(Diagnostics.Expression_or_comma_expected);
|
||||
case ParsingContext.JSDocParameters: return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected);
|
||||
case ParsingContext.Parameters: return parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected);
|
||||
case ParsingContext.Parameters:
|
||||
return isKeyword(token())
|
||||
? parseErrorAtCurrentToken(Diagnostics._0_is_not_allowed_as_a_parameter_name, tokenToString(token()))
|
||||
: parseErrorAtCurrentToken(Diagnostics.Parameter_declaration_expected);
|
||||
case ParsingContext.TypeParameters: return parseErrorAtCurrentToken(Diagnostics.Type_parameter_declaration_expected);
|
||||
case ParsingContext.TypeArguments: return parseErrorAtCurrentToken(Diagnostics.Type_argument_expected);
|
||||
case ParsingContext.TupleElementTypes: return parseErrorAtCurrentToken(Diagnostics.Type_expected);
|
||||
@@ -2702,7 +2720,7 @@ namespace ts {
|
||||
return createMissingList<T>();
|
||||
}
|
||||
|
||||
function parseEntityName(allowReservedWords: boolean, diagnosticMessage?: DiagnosticMessage): EntityName {
|
||||
function parseEntityName(allowReservedWords: boolean, allowPrivateIdentifiers: boolean, diagnosticMessage?: DiagnosticMessage): EntityName {
|
||||
const pos = getNodePos();
|
||||
let entity: EntityName = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
|
||||
let dotPos = getNodePos();
|
||||
@@ -2716,7 +2734,7 @@ namespace ts {
|
||||
entity = finishNode(
|
||||
factory.createQualifiedName(
|
||||
entity,
|
||||
parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false) as Identifier
|
||||
parseRightSideOfDot(allowReservedWords, allowPrivateIdentifiers) as Identifier
|
||||
),
|
||||
pos
|
||||
);
|
||||
@@ -2901,7 +2919,7 @@ namespace ts {
|
||||
// TYPES
|
||||
|
||||
function parseEntityNameOfTypeReference() {
|
||||
return parseEntityName(/*allowReservedWords*/ true, Diagnostics.Type_expected);
|
||||
return parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ false, Diagnostics.Type_expected);
|
||||
}
|
||||
|
||||
function parseTypeArgumentsOfTypeReference() {
|
||||
@@ -3061,7 +3079,9 @@ namespace ts {
|
||||
function parseTypeQuery(): TypeQueryNode {
|
||||
const pos = getNodePos();
|
||||
parseExpected(SyntaxKind.TypeOfKeyword);
|
||||
return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
|
||||
const entityName = parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ true);
|
||||
const typeArguments = tryParseTypeArguments();
|
||||
return finishNode(factory.createTypeQueryNode(entityName, typeArguments), pos);
|
||||
}
|
||||
|
||||
function parseTypeParameter(): TypeParameterDeclaration {
|
||||
@@ -3521,8 +3541,9 @@ namespace ts {
|
||||
}
|
||||
const type = parseTypeAnnotation();
|
||||
parseSemicolon();
|
||||
const members = parseList(ParsingContext.TypeMembers, parseTypeMember);
|
||||
parseExpected(SyntaxKind.CloseBraceToken);
|
||||
return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos);
|
||||
return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type, members), pos);
|
||||
}
|
||||
|
||||
function parseTupleElementType() {
|
||||
@@ -4415,7 +4436,7 @@ namespace ts {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
else if (third === SyntaxKind.CommaToken) {
|
||||
else if (third === SyntaxKind.CommaToken || third === SyntaxKind.EqualsToken) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -4521,9 +4542,16 @@ namespace ts {
|
||||
// - "(x,y)" is a comma expression parsed as a signature with two parameters.
|
||||
// - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
|
||||
// - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
|
||||
// - "a ? (b): (function() {})" as well, but inside of a parenthesized type with an arbitrary amount of nesting.
|
||||
//
|
||||
// So we need just a bit of lookahead to ensure that it can only be a signature.
|
||||
const hasJSDocFunctionType = type && isJSDocFunctionType(type);
|
||||
|
||||
let unwrappedType = type;
|
||||
while (unwrappedType?.kind === SyntaxKind.ParenthesizedType) {
|
||||
unwrappedType = (unwrappedType as ParenthesizedTypeNode).type; // Skip parens if need be
|
||||
}
|
||||
|
||||
const hasJSDocFunctionType = unwrappedType && isJSDocFunctionType(unwrappedType);
|
||||
if (!allowAmbiguity && token() !== SyntaxKind.EqualsGreaterThanToken && (hasJSDocFunctionType || token() !== SyntaxKind.OpenBraceToken)) {
|
||||
// Returning undefined here will cause our caller to rewind to where we started from.
|
||||
return undefined;
|
||||
@@ -5042,12 +5070,12 @@ namespace ts {
|
||||
&& !tagNamesAreEquivalent(lastChild.openingElement.tagName, lastChild.closingElement.tagName)
|
||||
&& tagNamesAreEquivalent(opening.tagName, lastChild.closingElement.tagName)) {
|
||||
// when an unclosed JsxOpeningElement incorrectly parses its parent's JsxClosingElement,
|
||||
// restructure (<div>(...<span></div>)) --> (<div>(...<span></span>)</div>)
|
||||
// restructure (<div>(...<span>...</div>)) --> (<div>(...<span>...</>)</div>)
|
||||
// (no need to error; the parent will error)
|
||||
const end = lastChild.openingElement.end; // newly-created children and closing are both zero-width end/end
|
||||
const end = lastChild.children.end;
|
||||
const newLast = finishNode(factory.createJsxElement(
|
||||
lastChild.openingElement,
|
||||
createNodeArray([], end, end),
|
||||
lastChild.children,
|
||||
finishNode(factory.createJsxClosingElement(finishNode(factory.createIdentifier(""), end, end)), end, end)),
|
||||
lastChild.openingElement.pos,
|
||||
end);
|
||||
@@ -5403,12 +5431,6 @@ namespace ts {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!questionDotToken && token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
|
||||
nextToken();
|
||||
expression = finishNode(factory.createNonNullExpression(expression), pos);
|
||||
continue;
|
||||
}
|
||||
|
||||
// when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
|
||||
if ((questionDotToken || !inDecoratorContext()) && parseOptional(SyntaxKind.OpenBracketToken)) {
|
||||
expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
|
||||
@@ -5416,10 +5438,26 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (isTemplateStartOfTaggedTemplate()) {
|
||||
expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
|
||||
// Absorb type arguments into TemplateExpression when preceding expression is ExpressionWithTypeArguments
|
||||
expression = !questionDotToken && expression.kind === SyntaxKind.ExpressionWithTypeArguments ?
|
||||
parseTaggedTemplateRest(pos, (expression as ExpressionWithTypeArguments).expression, questionDotToken, (expression as ExpressionWithTypeArguments).typeArguments) :
|
||||
parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!questionDotToken) {
|
||||
if (token() === SyntaxKind.ExclamationToken && !scanner.hasPrecedingLineBreak()) {
|
||||
nextToken();
|
||||
expression = finishNode(factory.createNonNullExpression(expression), pos);
|
||||
continue;
|
||||
}
|
||||
const typeArguments = tryParse(parseTypeArgumentsInExpression);
|
||||
if (typeArguments) {
|
||||
expression = finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return expression as MemberExpression;
|
||||
}
|
||||
}
|
||||
@@ -5446,39 +5484,30 @@ namespace ts {
|
||||
function parseCallExpressionRest(pos: number, expression: LeftHandSideExpression): LeftHandSideExpression {
|
||||
while (true) {
|
||||
expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
|
||||
let typeArguments: NodeArray<TypeNode> | undefined;
|
||||
const questionDotToken = parseOptionalToken(SyntaxKind.QuestionDotToken);
|
||||
// handle 'foo<<T>()'
|
||||
// parse template arguments only in TypeScript files (not in JavaScript files).
|
||||
if ((contextFlags & NodeFlags.JavaScriptFile) === 0 && (token() === SyntaxKind.LessThanToken || token() === SyntaxKind.LessThanLessThanToken)) {
|
||||
// See if this is the start of a generic invocation. If so, consume it and
|
||||
// keep checking for postfix expressions. Otherwise, it's just a '<' that's
|
||||
// part of an arithmetic expression. Break out so we consume it higher in the
|
||||
// stack.
|
||||
const typeArguments = tryParse(parseTypeArgumentsInExpression);
|
||||
if (typeArguments) {
|
||||
if (isTemplateStartOfTaggedTemplate()) {
|
||||
expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
|
||||
continue;
|
||||
}
|
||||
|
||||
const argumentList = parseArgumentList();
|
||||
const callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
|
||||
factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
|
||||
factory.createCallExpression(expression, typeArguments, argumentList);
|
||||
expression = finishNode(callExpr, pos);
|
||||
if (questionDotToken) {
|
||||
typeArguments = tryParse(parseTypeArgumentsInExpression);
|
||||
if (isTemplateStartOfTaggedTemplate()) {
|
||||
expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else if (token() === SyntaxKind.OpenParenToken) {
|
||||
if (typeArguments || token() === SyntaxKind.OpenParenToken) {
|
||||
// Absorb type arguments into CallExpression when preceding expression is ExpressionWithTypeArguments
|
||||
if (!questionDotToken && expression.kind === SyntaxKind.ExpressionWithTypeArguments) {
|
||||
typeArguments = (expression as ExpressionWithTypeArguments).typeArguments;
|
||||
expression = (expression as ExpressionWithTypeArguments).expression;
|
||||
}
|
||||
const argumentList = parseArgumentList();
|
||||
const callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
|
||||
factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
|
||||
factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
|
||||
factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
|
||||
factory.createCallExpression(expression, typeArguments, argumentList);
|
||||
expression = finishNode(callExpr, pos);
|
||||
continue;
|
||||
}
|
||||
if (questionDotToken) {
|
||||
// We failed to parse anything, so report a missing identifier here.
|
||||
// We parsed `?.` but then failed to parse anything, so report a missing identifier here.
|
||||
const name = createMissingNode<Identifier>(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ false, Diagnostics.Identifier_expected);
|
||||
expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
|
||||
}
|
||||
@@ -5511,22 +5540,26 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// If we have a '<', then only parse this as a argument list if the type arguments
|
||||
// are complete and we have an open paren. if we don't, rewind and return nothing.
|
||||
return typeArguments && canFollowTypeArgumentsInExpression()
|
||||
? typeArguments
|
||||
: undefined;
|
||||
// We successfully parsed a type argument list. The next token determines whether we want to
|
||||
// treat it as such. If the type argument list is followed by `(` or a template literal, as in
|
||||
// `f<number>(42)`, we favor the type argument interpretation even though JavaScript would view
|
||||
// it as a relational expression.
|
||||
return typeArguments && canFollowTypeArgumentsInExpression() ? typeArguments : undefined;
|
||||
}
|
||||
|
||||
function canFollowTypeArgumentsInExpression(): boolean {
|
||||
switch (token()) {
|
||||
// These tokens can follow a type argument list in a call expression.
|
||||
case SyntaxKind.OpenParenToken: // foo<x>(
|
||||
case SyntaxKind.NoSubstitutionTemplateLiteral: // foo<T> `...`
|
||||
case SyntaxKind.TemplateHead: // foo<T> `...${100}...`
|
||||
// these are the only tokens can legally follow a type argument
|
||||
// list. So we definitely want to treat them as type arg lists.
|
||||
// These tokens can't follow in a call expression, nor can they start an
|
||||
// expression. So, consider the type argument list part of an instantiation
|
||||
// expression.
|
||||
// falls through
|
||||
case SyntaxKind.CommaToken: // foo<x>,
|
||||
case SyntaxKind.DotToken: // foo<x>.
|
||||
case SyntaxKind.QuestionDotToken: // foo<x>?.
|
||||
case SyntaxKind.CloseParenToken: // foo<x>)
|
||||
case SyntaxKind.CloseBracketToken: // foo<x>]
|
||||
case SyntaxKind.ColonToken: // foo<x>:
|
||||
@@ -5544,21 +5577,10 @@ namespace ts {
|
||||
case SyntaxKind.BarToken: // foo<x> |
|
||||
case SyntaxKind.CloseBraceToken: // foo<x> }
|
||||
case SyntaxKind.EndOfFileToken: // foo<x>
|
||||
// these cases can't legally follow a type arg list. However, they're not legal
|
||||
// expressions either. The user is probably in the middle of a generic type. So
|
||||
// treat it as such.
|
||||
return true;
|
||||
|
||||
case SyntaxKind.CommaToken: // foo<x>,
|
||||
case SyntaxKind.OpenBraceToken: // foo<x> {
|
||||
// We don't want to treat these as type arguments. Otherwise we'll parse this
|
||||
// as an invocation expression. Instead, we want to parse out the expression
|
||||
// in isolation from the type arguments.
|
||||
// falls through
|
||||
default:
|
||||
// Anything else treat as an expression.
|
||||
return false;
|
||||
}
|
||||
// Treat anything else as an expression.
|
||||
return false;
|
||||
}
|
||||
|
||||
function parsePrimaryExpression(): PrimaryExpression {
|
||||
@@ -5603,6 +5625,8 @@ namespace ts {
|
||||
break;
|
||||
case SyntaxKind.TemplateHead:
|
||||
return parseTemplateExpression(/* isTaggedTemplate */ false);
|
||||
case SyntaxKind.PrivateIdentifier:
|
||||
return parsePrivateIdentifier();
|
||||
}
|
||||
|
||||
return parseIdentifier(Diagnostics.Expression_expected);
|
||||
@@ -5763,30 +5787,16 @@ namespace ts {
|
||||
const name = parseIdentifierName();
|
||||
return finishNode(factory.createMetaProperty(SyntaxKind.NewKeyword, name), pos);
|
||||
}
|
||||
|
||||
const expressionPos = getNodePos();
|
||||
let expression: MemberExpression = parsePrimaryExpression();
|
||||
let typeArguments;
|
||||
while (true) {
|
||||
expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
|
||||
typeArguments = tryParse(parseTypeArgumentsInExpression);
|
||||
if (isTemplateStartOfTaggedTemplate()) {
|
||||
Debug.assert(!!typeArguments,
|
||||
"Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
|
||||
expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
|
||||
typeArguments = undefined;
|
||||
}
|
||||
break;
|
||||
let expression: LeftHandSideExpression = parseMemberExpressionRest(expressionPos, parsePrimaryExpression(), /*allowOptionalChain*/ false);
|
||||
let typeArguments: NodeArray<TypeNode> | undefined;
|
||||
// Absorb type arguments into NewExpression when preceding expression is ExpressionWithTypeArguments
|
||||
if (expression.kind === SyntaxKind.ExpressionWithTypeArguments) {
|
||||
typeArguments = (expression as ExpressionWithTypeArguments).typeArguments;
|
||||
expression = (expression as ExpressionWithTypeArguments).expression;
|
||||
}
|
||||
|
||||
let argumentsArray: NodeArray<Expression> | undefined;
|
||||
if (token() === SyntaxKind.OpenParenToken) {
|
||||
argumentsArray = parseArgumentList();
|
||||
}
|
||||
else if (typeArguments) {
|
||||
parseErrorAt(pos, scanner.getStartPos(), Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
|
||||
}
|
||||
return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
|
||||
const argumentList = token() === SyntaxKind.OpenParenToken ? parseArgumentList() : undefined;
|
||||
return finishNode(factory.createNewExpression(expression, typeArguments, argumentList), pos);
|
||||
}
|
||||
|
||||
// STATEMENTS
|
||||
@@ -5978,11 +5988,12 @@ namespace ts {
|
||||
|
||||
function parseCaseClause(): CaseClause {
|
||||
const pos = getNodePos();
|
||||
const hasJSDoc = hasPrecedingJSDocComment();
|
||||
parseExpected(SyntaxKind.CaseKeyword);
|
||||
const expression = allowInAnd(parseExpression);
|
||||
parseExpected(SyntaxKind.ColonToken);
|
||||
const statements = parseList(ParsingContext.SwitchClauseStatements, parseStatement);
|
||||
return finishNode(factory.createCaseClause(expression, statements), pos);
|
||||
return withJSDoc(finishNode(factory.createCaseClause(expression, statements), pos), hasJSDoc);
|
||||
}
|
||||
|
||||
function parseDefaultClause(): DefaultClause {
|
||||
@@ -6053,7 +6064,7 @@ namespace ts {
|
||||
// one out no matter what.
|
||||
let finallyBlock: Block | undefined;
|
||||
if (!catchClause || token() === SyntaxKind.FinallyKeyword) {
|
||||
parseExpected(SyntaxKind.FinallyKeyword);
|
||||
parseExpected(SyntaxKind.FinallyKeyword, Diagnostics.catch_or_finally_expected);
|
||||
finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
|
||||
}
|
||||
|
||||
@@ -6854,7 +6865,7 @@ namespace ts {
|
||||
return list && createNodeArray(list, pos);
|
||||
}
|
||||
|
||||
function tryParseModifier(permitInvalidConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): Modifier | undefined {
|
||||
function tryParseModifier(permitInvalidConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean, hasSeenStaticModifier?: boolean): Modifier | undefined {
|
||||
const pos = getNodePos();
|
||||
const kind = token();
|
||||
|
||||
@@ -6868,6 +6879,9 @@ namespace ts {
|
||||
else if (stopOnStartOfClassStaticBlock && token() === SyntaxKind.StaticKeyword && lookAhead(nextTokenIsOpenBrace)) {
|
||||
return undefined;
|
||||
}
|
||||
else if (hasSeenStaticModifier && token() === SyntaxKind.StaticKeyword) {
|
||||
return undefined;
|
||||
}
|
||||
else {
|
||||
if (!parseAnyContextualModifier()) {
|
||||
return undefined;
|
||||
@@ -6886,8 +6900,9 @@ namespace ts {
|
||||
*/
|
||||
function parseModifiers(permitInvalidConstAsModifier?: boolean, stopOnStartOfClassStaticBlock?: boolean): NodeArray<Modifier> | undefined {
|
||||
const pos = getNodePos();
|
||||
let list, modifier;
|
||||
while (modifier = tryParseModifier(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock)) {
|
||||
let list, modifier, hasSeenStatic = false;
|
||||
while (modifier = tryParseModifier(permitInvalidConstAsModifier, stopOnStartOfClassStaticBlock, hasSeenStatic)) {
|
||||
if (modifier.kind === SyntaxKind.StaticKeyword) hasSeenStatic = true;
|
||||
list = append(list, modifier);
|
||||
}
|
||||
return list && createNodeArray(list, pos);
|
||||
@@ -7039,6 +7054,9 @@ namespace ts {
|
||||
function parseExpressionWithTypeArguments(): ExpressionWithTypeArguments {
|
||||
const pos = getNodePos();
|
||||
const expression = parseLeftHandSideExpressionOrHigher();
|
||||
if (expression.kind === SyntaxKind.ExpressionWithTypeArguments) {
|
||||
return expression as ExpressionWithTypeArguments;
|
||||
}
|
||||
const typeArguments = tryParseTypeArguments();
|
||||
return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
|
||||
}
|
||||
@@ -7234,13 +7252,50 @@ namespace ts {
|
||||
importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
|
||||
parseExpected(SyntaxKind.FromKeyword);
|
||||
}
|
||||
|
||||
const moduleSpecifier = parseModuleSpecifier();
|
||||
|
||||
let assertClause: AssertClause | undefined;
|
||||
if (token() === SyntaxKind.AssertKeyword && !scanner.hasPrecedingLineBreak()) {
|
||||
assertClause = parseAssertClause();
|
||||
}
|
||||
|
||||
parseSemicolon();
|
||||
const node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier);
|
||||
const node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier, assertClause);
|
||||
return withJSDoc(finishNode(node, pos), hasJSDoc);
|
||||
}
|
||||
|
||||
function parseAssertEntry() {
|
||||
const pos = getNodePos();
|
||||
const name = tokenIsIdentifierOrKeyword(token()) ? parseIdentifierName() : parseLiteralLikeNode(SyntaxKind.StringLiteral) as StringLiteral;
|
||||
parseExpected(SyntaxKind.ColonToken);
|
||||
const value = parseAssignmentExpressionOrHigher();
|
||||
return finishNode(factory.createAssertEntry(name, value), pos);
|
||||
}
|
||||
|
||||
function parseAssertClause() {
|
||||
const pos = getNodePos();
|
||||
parseExpected(SyntaxKind.AssertKeyword);
|
||||
const openBracePosition = scanner.getTokenPos();
|
||||
if (parseExpected(SyntaxKind.OpenBraceToken)) {
|
||||
const multiLine = scanner.hasPrecedingLineBreak();
|
||||
const elements = parseDelimitedList(ParsingContext.AssertEntries, parseAssertEntry, /*considerSemicolonAsDelimiter*/ true);
|
||||
if (!parseExpected(SyntaxKind.CloseBraceToken)) {
|
||||
const lastError = lastOrUndefined(parseDiagnostics);
|
||||
if (lastError && lastError.code === Diagnostics._0_expected.code) {
|
||||
addRelatedInfo(
|
||||
lastError,
|
||||
createDetachedDiagnostic(fileName, openBracePosition, 1, Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here)
|
||||
);
|
||||
}
|
||||
}
|
||||
return finishNode(factory.createAssertClause(elements, multiLine), pos);
|
||||
}
|
||||
else {
|
||||
const elements = createNodeArray([], getNodePos(), /*end*/ undefined, /*hasTrailingComma*/ false);
|
||||
return finishNode(factory.createAssertClause(elements, /*multiLine*/ false), pos);
|
||||
}
|
||||
}
|
||||
|
||||
function tokenAfterImportDefinitelyProducesImportDeclaration() {
|
||||
return token() === SyntaxKind.AsteriskToken || token() === SyntaxKind.OpenBraceToken;
|
||||
}
|
||||
@@ -7282,7 +7337,7 @@ namespace ts {
|
||||
function parseModuleReference() {
|
||||
return isExternalModuleReference()
|
||||
? parseExternalModuleReference()
|
||||
: parseEntityName(/*allowReservedWords*/ false);
|
||||
: parseEntityName(/*allowReservedWords*/ false, /*allowPrivateIdentifiers*/ false);
|
||||
}
|
||||
|
||||
function parseExternalModuleReference() {
|
||||
@@ -7338,7 +7393,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
function parseExportSpecifier() {
|
||||
return parseImportOrExportSpecifier(SyntaxKind.ExportSpecifier) as ExportSpecifier;
|
||||
const hasJSDoc = hasPrecedingJSDocComment();
|
||||
return withJSDoc(parseImportOrExportSpecifier(SyntaxKind.ExportSpecifier) as ExportSpecifier, hasJSDoc);
|
||||
}
|
||||
|
||||
function parseImportSpecifier() {
|
||||
@@ -7356,27 +7412,76 @@ namespace ts {
|
||||
let checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier();
|
||||
let checkIdentifierStart = scanner.getTokenPos();
|
||||
let checkIdentifierEnd = scanner.getTextPos();
|
||||
const identifierName = parseIdentifierName();
|
||||
let isTypeOnly = false;
|
||||
let propertyName: Identifier | undefined;
|
||||
let name: Identifier;
|
||||
if (token() === SyntaxKind.AsKeyword) {
|
||||
propertyName = identifierName;
|
||||
parseExpected(SyntaxKind.AsKeyword);
|
||||
checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier();
|
||||
checkIdentifierStart = scanner.getTokenPos();
|
||||
checkIdentifierEnd = scanner.getTextPos();
|
||||
name = parseIdentifierName();
|
||||
let canParseAsKeyword = true;
|
||||
let name = parseIdentifierName();
|
||||
if (name.escapedText === "type") {
|
||||
// If the first token of an import specifier is 'type', there are a lot of possibilities,
|
||||
// especially if we see 'as' afterwards:
|
||||
//
|
||||
// import { type } from "mod"; - isTypeOnly: false, name: type
|
||||
// import { type as } from "mod"; - isTypeOnly: true, name: as
|
||||
// import { type as as } from "mod"; - isTypeOnly: false, name: as, propertyName: type
|
||||
// import { type as as as } from "mod"; - isTypeOnly: true, name: as, propertyName: as
|
||||
if (token() === SyntaxKind.AsKeyword) {
|
||||
// { type as ...? }
|
||||
const firstAs = parseIdentifierName();
|
||||
if (token() === SyntaxKind.AsKeyword) {
|
||||
// { type as as ...? }
|
||||
const secondAs = parseIdentifierName();
|
||||
if (tokenIsIdentifierOrKeyword(token())) {
|
||||
// { type as as something }
|
||||
isTypeOnly = true;
|
||||
propertyName = firstAs;
|
||||
name = parseNameWithKeywordCheck();
|
||||
canParseAsKeyword = false;
|
||||
}
|
||||
else {
|
||||
// { type as as }
|
||||
propertyName = name;
|
||||
name = secondAs;
|
||||
canParseAsKeyword = false;
|
||||
}
|
||||
}
|
||||
else if (tokenIsIdentifierOrKeyword(token())) {
|
||||
// { type as something }
|
||||
propertyName = name;
|
||||
canParseAsKeyword = false;
|
||||
name = parseNameWithKeywordCheck();
|
||||
}
|
||||
else {
|
||||
// { type as }
|
||||
isTypeOnly = true;
|
||||
name = firstAs;
|
||||
}
|
||||
}
|
||||
else if (tokenIsIdentifierOrKeyword(token())) {
|
||||
// { type something ...? }
|
||||
isTypeOnly = true;
|
||||
name = parseNameWithKeywordCheck();
|
||||
}
|
||||
}
|
||||
else {
|
||||
name = identifierName;
|
||||
|
||||
if (canParseAsKeyword && token() === SyntaxKind.AsKeyword) {
|
||||
propertyName = name;
|
||||
parseExpected(SyntaxKind.AsKeyword);
|
||||
name = parseNameWithKeywordCheck();
|
||||
}
|
||||
if (kind === SyntaxKind.ImportSpecifier && checkIdentifierIsKeyword) {
|
||||
parseErrorAt(checkIdentifierStart, checkIdentifierEnd, Diagnostics.Identifier_expected);
|
||||
}
|
||||
const node = kind === SyntaxKind.ImportSpecifier
|
||||
? factory.createImportSpecifier(propertyName, name)
|
||||
: factory.createExportSpecifier(propertyName, name);
|
||||
? factory.createImportSpecifier(isTypeOnly, propertyName, name)
|
||||
: factory.createExportSpecifier(isTypeOnly, propertyName, name);
|
||||
return finishNode(node, pos);
|
||||
|
||||
function parseNameWithKeywordCheck() {
|
||||
checkIdentifierIsKeyword = isKeyword(token()) && !isIdentifier();
|
||||
checkIdentifierStart = scanner.getTokenPos();
|
||||
checkIdentifierEnd = scanner.getTextPos();
|
||||
return parseIdentifierName();
|
||||
}
|
||||
}
|
||||
|
||||
function parseNamespaceExport(pos: number): NamespaceExport {
|
||||
@@ -7388,6 +7493,7 @@ namespace ts {
|
||||
setAwaitContext(/*value*/ true);
|
||||
let exportClause: NamedExportBindings | undefined;
|
||||
let moduleSpecifier: Expression | undefined;
|
||||
let assertClause: AssertClause | undefined;
|
||||
const isTypeOnly = parseOptional(SyntaxKind.TypeKeyword);
|
||||
const namespaceExportPos = getNodePos();
|
||||
if (parseOptional(SyntaxKind.AsteriskToken)) {
|
||||
@@ -7407,9 +7513,12 @@ namespace ts {
|
||||
moduleSpecifier = parseModuleSpecifier();
|
||||
}
|
||||
}
|
||||
if (moduleSpecifier && token() === SyntaxKind.AssertKeyword && !scanner.hasPrecedingLineBreak()) {
|
||||
assertClause = parseAssertClause();
|
||||
}
|
||||
parseSemicolon();
|
||||
setAwaitContext(savedAwaitContext);
|
||||
const node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier);
|
||||
const node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, assertClause);
|
||||
return withJSDoc(finishNode(node, pos), hasJSDoc);
|
||||
}
|
||||
|
||||
@@ -7489,7 +7598,8 @@ namespace ts {
|
||||
TypeArguments, // Type arguments in type argument list
|
||||
TupleElementTypes, // Element types in tuple element type list
|
||||
HeritageClauses, // Heritage clauses for a class or interface declaration.
|
||||
ImportOrExportSpecifiers, // Named import clause's import specifier list
|
||||
ImportOrExportSpecifiers, // Named import clause's import specifier list,
|
||||
AssertEntries, // Import entries list.
|
||||
Count // Number of parsing contexts
|
||||
}
|
||||
|
||||
@@ -7535,7 +7645,7 @@ namespace ts {
|
||||
const pos = getNodePos();
|
||||
const hasBrace = parseOptional(SyntaxKind.OpenBraceToken);
|
||||
const p2 = getNodePos();
|
||||
let entityName: EntityName | JSDocMemberName = parseEntityName(/* allowReservedWords*/ false);
|
||||
let entityName: EntityName | JSDocMemberName = parseEntityName(/* allowReservedWords*/ false, /*allowPrivateIdentifiers*/ false);
|
||||
while (token() === SyntaxKind.PrivateIdentifier) {
|
||||
reScanHashToken(); // rescan #id as # id
|
||||
nextTokenJSDoc(); // then skip the #
|
||||
@@ -7998,7 +8108,7 @@ namespace ts {
|
||||
// parseEntityName logs an error for non-identifier, so create a MissingNode ourselves to avoid the error
|
||||
const p2 = getNodePos();
|
||||
let name: EntityName | JSDocMemberName | undefined = tokenIsIdentifierOrKeyword(token())
|
||||
? parseEntityName(/*allowReservedWords*/ true)
|
||||
? parseEntityName(/*allowReservedWords*/ true, /*allowPrivateIdentifiers*/ false)
|
||||
: undefined;
|
||||
if (name) {
|
||||
while (token() === SyntaxKind.PrivateIdentifier) {
|
||||
@@ -8024,12 +8134,14 @@ namespace ts {
|
||||
&& nextTokenJSDoc() === SyntaxKind.AtToken
|
||||
&& tokenIsIdentifierOrKeyword(nextTokenJSDoc())) {
|
||||
const kind = scanner.getTokenValue();
|
||||
if(kind === "link" || kind === "linkcode" || kind === "linkplain") {
|
||||
return kind;
|
||||
}
|
||||
if (isJSDocLinkTag(kind)) return kind;
|
||||
}
|
||||
}
|
||||
|
||||
function isJSDocLinkTag(kind: string) {
|
||||
return kind === "link" || kind === "linkcode" || kind === "linkplain";
|
||||
}
|
||||
|
||||
function parseUnknownTag(start: number, tagName: Identifier, indent: number, indentText: string) {
|
||||
return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, getNodePos(), indent, indentText)), start);
|
||||
}
|
||||
@@ -8151,8 +8263,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
function parseSeeTag(start: number, tagName: Identifier, indent?: number, indentText?: string): JSDocSeeTag {
|
||||
const isLink = lookAhead(() => nextTokenJSDoc() === SyntaxKind.AtToken && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenValue() === "link");
|
||||
const nameExpression = isLink ? undefined : parseJSDocNameReference();
|
||||
const isMarkdownOrJSDocLink = token() === SyntaxKind.OpenBracketToken
|
||||
|| lookAhead(() => nextTokenJSDoc() === SyntaxKind.AtToken && tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && isJSDocLinkTag(scanner.getTokenValue()));
|
||||
const nameExpression = isMarkdownOrJSDocLink ? undefined : parseJSDocNameReference();
|
||||
const comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, getNodePos(), indent, indentText) : undefined;
|
||||
return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start);
|
||||
}
|
||||
@@ -8624,6 +8737,7 @@ namespace ts {
|
||||
newText,
|
||||
aggressiveChecks
|
||||
);
|
||||
result.impliedNodeFormat = sourceFile.impliedNodeFormat;
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -9164,7 +9278,7 @@ namespace ts {
|
||||
|
||||
/** @internal */
|
||||
export function isDeclarationFileName(fileName: string): boolean {
|
||||
return fileExtensionIs(fileName, Extension.Dts);
|
||||
return fileExtensionIsOneOf(fileName, [Extension.Dts, Extension.Dmts, Extension.Dcts]);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
@@ -9180,6 +9294,20 @@ namespace ts {
|
||||
moduleName?: string;
|
||||
}
|
||||
|
||||
function parseResolutionMode(mode: string | undefined, pos: number, end: number, reportDiagnostic: PragmaDiagnosticReporter): ModuleKind.ESNext | ModuleKind.CommonJS | undefined {
|
||||
if (!mode) {
|
||||
return undefined;
|
||||
}
|
||||
if (mode === "import") {
|
||||
return ModuleKind.ESNext;
|
||||
}
|
||||
if (mode === "require") {
|
||||
return ModuleKind.CommonJS;
|
||||
}
|
||||
reportDiagnostic(pos, end - pos, Diagnostics.resolution_mode_should_be_either_require_or_import);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export function processCommentPragmas(context: PragmaContext, sourceText: string): void {
|
||||
const pragmas: PragmaPseudoMapEntry[] = [];
|
||||
@@ -9225,12 +9353,13 @@ namespace ts {
|
||||
const typeReferenceDirectives = context.typeReferenceDirectives;
|
||||
const libReferenceDirectives = context.libReferenceDirectives;
|
||||
forEach(toArray(entryOrList) as PragmaPseudoMap["reference"][], arg => {
|
||||
const { types, lib, path } = arg.arguments;
|
||||
const { types, lib, path, ["resolution-mode"]: res } = arg.arguments;
|
||||
if (arg.arguments["no-default-lib"]) {
|
||||
context.hasNoDefaultLib = true;
|
||||
}
|
||||
else if (types) {
|
||||
typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value });
|
||||
const parsed = parseResolutionMode(res, types.pos, types.end, reportDiagnostic);
|
||||
typeReferenceDirectives.push({ pos: types.pos, end: types.end, fileName: types.value, ...(parsed ? { resolutionMode: parsed } : {}) });
|
||||
}
|
||||
else if (lib) {
|
||||
libReferenceDirectives.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
|
||||
|
||||
@@ -585,18 +585,6 @@ namespace ts {
|
||||
return getCanonicalFileName(nonCanonicalizedPath) as Path;
|
||||
}
|
||||
|
||||
export function normalizePathAndParts(path: string): { path: string, parts: string[] } {
|
||||
path = normalizeSlashes(path);
|
||||
const [root, ...parts] = reducePathComponents(getPathComponents(path));
|
||||
if (parts.length) {
|
||||
const joinedParts = root + parts.join(directorySeparator);
|
||||
return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts };
|
||||
}
|
||||
else {
|
||||
return { path: root, parts };
|
||||
}
|
||||
}
|
||||
|
||||
//// Path Mutation
|
||||
|
||||
/**
|
||||
|
||||
+328
-74
@@ -510,7 +510,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function loadWithLocalCache<T>(names: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, loader: (name: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => T): T[] {
|
||||
export function loadWithTypeDirectiveCache<T>(names: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, containingFileMode: SourceFile["impliedNodeFormat"], loader: (name: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined, resolutionMode: SourceFile["impliedNodeFormat"]) => T): T[] {
|
||||
if (names.length === 0) {
|
||||
return [];
|
||||
}
|
||||
@@ -518,11 +518,72 @@ namespace ts {
|
||||
const cache = new Map<string, T>();
|
||||
for (const name of names) {
|
||||
let result: T;
|
||||
if (cache.has(name)) {
|
||||
result = cache.get(name)!;
|
||||
const mode = getModeForFileReference(name, containingFileMode);
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const strName = isString(name) ? name : name.fileName.toLowerCase();
|
||||
const cacheKey = mode !== undefined ? `${mode}|${strName}` : strName;
|
||||
if (cache.has(cacheKey)) {
|
||||
result = cache.get(cacheKey)!;
|
||||
}
|
||||
else {
|
||||
cache.set(name, result = loader(name, containingFile, redirectedReference));
|
||||
cache.set(cacheKey, result = loader(strName, containingFile, redirectedReference, mode));
|
||||
}
|
||||
resolutions.push(result);
|
||||
}
|
||||
return resolutions;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
interface SourceFileImportsList {
|
||||
imports: SourceFile["imports"];
|
||||
moduleAugmentations: SourceFile["moduleAugmentations"];
|
||||
impliedNodeFormat?: SourceFile["impliedNodeFormat"];
|
||||
};
|
||||
|
||||
/* @internal */
|
||||
export function getModeForFileReference(ref: FileReference | string, containingFileMode: SourceFile["impliedNodeFormat"]) {
|
||||
return (isString(ref) ? containingFileMode : ref.resolutionMode) || containingFileMode;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function getModeForResolutionAtIndex(file: SourceFileImportsList, index: number) {
|
||||
if (file.impliedNodeFormat === undefined) return undefined;
|
||||
// we ensure all elements of file.imports and file.moduleAugmentations have the relevant parent pointers set during program setup,
|
||||
// so it's safe to use them even pre-bind
|
||||
return getModeForUsageLocation(file, getModuleNameStringLiteralAt(file, index));
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function getModeForUsageLocation(file: {impliedNodeFormat?: SourceFile["impliedNodeFormat"]}, usage: StringLiteralLike) {
|
||||
if (file.impliedNodeFormat === undefined) return undefined;
|
||||
if (file.impliedNodeFormat !== ModuleKind.ESNext) {
|
||||
// in cjs files, import call expressions are esm format, otherwise everything is cjs
|
||||
return isImportCall(walkUpParenthesizedExpressions(usage.parent)) ? ModuleKind.ESNext : ModuleKind.CommonJS;
|
||||
}
|
||||
// in esm files, import=require statements are cjs format, otherwise everything is esm
|
||||
// imports are only parent'd up to their containing declaration/expression, so access farther parents with care
|
||||
const exprParentParent = walkUpParenthesizedExpressions(usage.parent)?.parent;
|
||||
return exprParentParent && isImportEqualsDeclaration(exprParentParent) ? ModuleKind.CommonJS : ModuleKind.ESNext;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function loadWithModeAwareCache<T>(names: string[], containingFile: SourceFile, containingFileName: string, redirectedReference: ResolvedProjectReference | undefined, loader: (name: string, resolverMode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, containingFileName: string, redirectedReference: ResolvedProjectReference | undefined) => T): T[] {
|
||||
if (names.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const resolutions: T[] = [];
|
||||
const cache = new Map<string, T>();
|
||||
let i = 0;
|
||||
for (const name of names) {
|
||||
let result: T;
|
||||
const mode = getModeForResolutionAtIndex(containingFile, i);
|
||||
i++;
|
||||
const cacheKey = mode !== undefined ? `${mode}|${name}` : name;
|
||||
if (cache.has(cacheKey)) {
|
||||
result = cache.get(cacheKey)!;
|
||||
}
|
||||
else {
|
||||
cache.set(cacheKey, result = loader(name, mode, containingFileName, redirectedReference));
|
||||
}
|
||||
resolutions.push(result);
|
||||
}
|
||||
@@ -619,11 +680,11 @@ namespace ts {
|
||||
export function getReferencedFileLocation(getSourceFileByPath: (path: Path) => SourceFile | undefined, ref: ReferencedFile): ReferenceFileLocation | SyntheticReferenceFileLocation {
|
||||
const file = Debug.checkDefined(getSourceFileByPath(ref.file));
|
||||
const { kind, index } = ref;
|
||||
let pos: number | undefined, end: number | undefined, packageId: PackageId | undefined;
|
||||
let pos: number | undefined, end: number | undefined, packageId: PackageId | undefined, resolutionMode: FileReference["resolutionMode"] | undefined;
|
||||
switch (kind) {
|
||||
case FileIncludeKind.Import:
|
||||
const importLiteral = getModuleNameStringLiteralAt(file, index);
|
||||
packageId = file.resolvedModules?.get(importLiteral.text)?.packageId;
|
||||
packageId = file.resolvedModules?.get(importLiteral.text, getModeForResolutionAtIndex(file, index))?.packageId;
|
||||
if (importLiteral.pos === -1) return { file, packageId, text: importLiteral.text };
|
||||
pos = skipTrivia(file.text, importLiteral.pos);
|
||||
end = importLiteral.end;
|
||||
@@ -632,8 +693,8 @@ namespace ts {
|
||||
({ pos, end } = file.referencedFiles[index]);
|
||||
break;
|
||||
case FileIncludeKind.TypeReferenceDirective:
|
||||
({ pos, end } = file.typeReferenceDirectives[index]);
|
||||
packageId = file.resolvedTypeReferenceDirectiveNames?.get(toFileNameLowerCase(file.typeReferenceDirectives[index].fileName))?.packageId;
|
||||
({ pos, end, resolutionMode } = file.typeReferenceDirectives[index]);
|
||||
packageId = file.resolvedTypeReferenceDirectiveNames?.get(toFileNameLowerCase(file.typeReferenceDirectives[index].fileName), resolutionMode || file.impliedNodeFormat)?.packageId;
|
||||
break;
|
||||
case FileIncludeKind.LibReferenceDirective:
|
||||
({ pos, end } = file.libReferenceDirectives[index]);
|
||||
@@ -738,6 +799,129 @@ namespace ts {
|
||||
configFileParseResult.errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* A function for determining if a given file is esm or cjs format, assuming modern node module resolution rules, as configured by the
|
||||
* `options` parameter.
|
||||
*
|
||||
* @param fileName The normalized absolute path to check the format of (it need not exist on disk)
|
||||
* @param [packageJsonInfoCache] A cache for package file lookups - it's best to have a cache when this function is called often
|
||||
* @param host The ModuleResolutionHost which can perform the filesystem lookups for package json data
|
||||
* @param options The compiler options to perform the analysis under - relevant options are `moduleResolution` and `traceResolution`
|
||||
* @returns `undefined` if the path has no relevant implied format, `ModuleKind.ESNext` for esm format, and `ModuleKind.CommonJS` for cjs format
|
||||
*/
|
||||
export function getImpliedNodeFormatForFile(fileName: Path, packageJsonInfoCache: PackageJsonInfoCache | undefined, host: ModuleResolutionHost, options: CompilerOptions): ModuleKind.ESNext | ModuleKind.CommonJS | undefined {
|
||||
switch (getEmitModuleResolutionKind(options)) {
|
||||
case ModuleResolutionKind.Node12:
|
||||
case ModuleResolutionKind.NodeNext:
|
||||
return fileExtensionIsOneOf(fileName, [Extension.Dmts, Extension.Mts, Extension.Mjs]) ? ModuleKind.ESNext :
|
||||
fileExtensionIsOneOf(fileName, [Extension.Dcts, Extension.Cts, Extension.Cjs]) ? ModuleKind.CommonJS :
|
||||
fileExtensionIsOneOf(fileName, [Extension.Dts, Extension.Ts, Extension.Tsx, Extension.Js, Extension.Jsx]) ? lookupFromPackageJson() :
|
||||
undefined; // other extensions, like `json` or `tsbuildinfo`, are set as `undefined` here but they should never be fed through the transformer pipeline
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
function lookupFromPackageJson(): ModuleKind.ESNext | ModuleKind.CommonJS {
|
||||
const scope = getPackageScopeForPath(fileName, packageJsonInfoCache, host, options);
|
||||
return scope?.packageJsonContent.type === "module" ? ModuleKind.ESNext : ModuleKind.CommonJS;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const plainJSErrors: Set<number> = new Set([
|
||||
// binder errors
|
||||
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,
|
||||
// grammar errors
|
||||
Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement.code,
|
||||
Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement.code,
|
||||
Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name.code,
|
||||
Diagnostics.A_class_member_cannot_have_the_0_keyword.code,
|
||||
Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name.code,
|
||||
Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement.code,
|
||||
Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code,
|
||||
Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement.code,
|
||||
Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement.code,
|
||||
Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration.code,
|
||||
Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context.code,
|
||||
Diagnostics.A_destructuring_declaration_must_have_an_initializer.code,
|
||||
Diagnostics.A_get_accessor_cannot_have_parameters.code,
|
||||
Diagnostics.A_rest_element_cannot_contain_a_binding_pattern.code,
|
||||
Diagnostics.A_rest_element_cannot_have_a_property_name.code,
|
||||
Diagnostics.A_rest_element_cannot_have_an_initializer.code,
|
||||
Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern.code,
|
||||
Diagnostics.A_rest_parameter_cannot_have_an_initializer.code,
|
||||
Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list.code,
|
||||
Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma.code,
|
||||
Diagnostics.A_return_statement_can_only_be_used_within_a_function_body.code,
|
||||
Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block.code,
|
||||
Diagnostics.A_set_accessor_cannot_have_rest_parameter.code,
|
||||
Diagnostics.A_set_accessor_must_have_exactly_one_parameter.code,
|
||||
Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module.code,
|
||||
Diagnostics.An_export_declaration_cannot_have_modifiers.code,
|
||||
Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module.code,
|
||||
Diagnostics.An_import_declaration_cannot_have_modifiers.code,
|
||||
Diagnostics.An_object_member_cannot_be_declared_optional.code,
|
||||
Diagnostics.Argument_of_dynamic_import_cannot_be_spread_element.code,
|
||||
Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable.code,
|
||||
Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause.code,
|
||||
Diagnostics.Catch_clause_variable_cannot_have_an_initializer.code,
|
||||
Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator.code,
|
||||
Diagnostics.Classes_can_only_extend_a_single_class.code,
|
||||
Diagnostics.Classes_may_not_have_a_field_named_constructor.code,
|
||||
Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern.code,
|
||||
Diagnostics.Duplicate_label_0.code,
|
||||
Diagnostics.Dynamic_imports_can_only_accept_a_module_specifier_and_an_optional_assertion_as_arguments.code,
|
||||
Diagnostics.For_await_loops_cannot_be_used_inside_a_class_static_block.code,
|
||||
Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression.code,
|
||||
Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name.code,
|
||||
Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array.code,
|
||||
Diagnostics.JSX_property_access_expressions_cannot_include_JSX_namespace_names.code,
|
||||
Diagnostics.Jump_target_cannot_cross_function_boundary.code,
|
||||
Diagnostics.Line_terminator_not_permitted_before_arrow.code,
|
||||
Diagnostics.Modifiers_cannot_appear_here.code,
|
||||
Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement.code,
|
||||
Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement.code,
|
||||
Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies.code,
|
||||
Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression.code,
|
||||
Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier.code,
|
||||
Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain.code,
|
||||
Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_async.code,
|
||||
Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer.code,
|
||||
Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer.code,
|
||||
Diagnostics.Trailing_comma_not_allowed.code,
|
||||
Diagnostics.Variable_declaration_list_cannot_be_empty.code,
|
||||
Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses.code,
|
||||
Diagnostics._0_expected.code,
|
||||
Diagnostics._0_is_not_a_valid_meta_property_for_keyword_1_Did_you_mean_2.code,
|
||||
Diagnostics._0_list_cannot_be_empty.code,
|
||||
Diagnostics._0_modifier_already_seen.code,
|
||||
Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration.code,
|
||||
Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element.code,
|
||||
Diagnostics._0_modifier_cannot_appear_on_a_parameter.code,
|
||||
Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind.code,
|
||||
Diagnostics._0_modifier_cannot_be_used_here.code,
|
||||
Diagnostics._0_modifier_must_precede_1_modifier.code,
|
||||
Diagnostics.const_declarations_can_only_be_declared_inside_a_block.code,
|
||||
Diagnostics.const_declarations_must_be_initialized.code,
|
||||
Diagnostics.extends_clause_already_seen.code,
|
||||
Diagnostics.let_declarations_can_only_be_declared_inside_a_block.code,
|
||||
Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations.code,
|
||||
]);
|
||||
|
||||
/**
|
||||
* Determine if source file needs to be re-created even if its text hasn't changed
|
||||
*/
|
||||
@@ -802,7 +986,7 @@ namespace ts {
|
||||
const cachedBindAndCheckDiagnosticsForFile: DiagnosticCache<Diagnostic> = {};
|
||||
const cachedDeclarationDiagnosticsForFile: DiagnosticCache<DiagnosticWithLocation> = {};
|
||||
|
||||
let resolvedTypeReferenceDirectives = new Map<string, ResolvedTypeReferenceDirective | undefined>();
|
||||
let resolvedTypeReferenceDirectives = createModeAwareCache<ResolvedTypeReferenceDirective | undefined>();
|
||||
let fileProcessingDiagnostics: FilePreprocessingDiagnostics[] | undefined;
|
||||
|
||||
// The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
|
||||
@@ -834,7 +1018,7 @@ namespace ts {
|
||||
const programDiagnostics = createDiagnosticCollection();
|
||||
const currentDirectory = host.getCurrentDirectory();
|
||||
const supportedExtensions = getSupportedExtensions(options);
|
||||
const supportedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
|
||||
const supportedExtensionsWithJsonIfResolveJsonModule = getSupportedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
|
||||
|
||||
// Map storing if there is emit blocking diagnostics for given input
|
||||
const hasEmitBlockingDiagnostics = new Map<string, boolean>();
|
||||
@@ -842,10 +1026,10 @@ namespace ts {
|
||||
|
||||
let moduleResolutionCache: ModuleResolutionCache | undefined;
|
||||
let typeReferenceDirectiveResolutionCache: TypeReferenceDirectiveResolutionCache | undefined;
|
||||
let actualResolveModuleNamesWorker: (moduleNames: string[], containingFile: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[];
|
||||
let actualResolveModuleNamesWorker: (moduleNames: string[], containingFile: SourceFile, containingFileName: string, reusedNames?: string[], redirectedReference?: ResolvedProjectReference) => ResolvedModuleFull[];
|
||||
const hasInvalidatedResolution = host.hasInvalidatedResolution || returnFalse;
|
||||
if (host.resolveModuleNames) {
|
||||
actualResolveModuleNamesWorker = (moduleNames, containingFile, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(resolved => {
|
||||
actualResolveModuleNamesWorker = (moduleNames, containingFile, containingFileName, reusedNames, redirectedReference) => host.resolveModuleNames!(Debug.checkEachDefined(moduleNames), containingFileName, reusedNames, redirectedReference, options, containingFile).map(resolved => {
|
||||
// An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
|
||||
if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) {
|
||||
return resolved as ResolvedModuleFull;
|
||||
@@ -854,28 +1038,30 @@ namespace ts {
|
||||
withExtension.extension = extensionFromPath(resolved.resolvedFileName);
|
||||
return withExtension;
|
||||
});
|
||||
moduleResolutionCache = host.getModuleResolutionCache?.();
|
||||
}
|
||||
else {
|
||||
moduleResolutionCache = createModuleResolutionCache(currentDirectory, getCanonicalFileName, options);
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule!; // TODO: GH#18217
|
||||
actualResolveModuleNamesWorker = (moduleNames, containingFile, _reusedNames, redirectedReference) => loadWithLocalCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
const loader = (moduleName: string, resolverMode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, containingFileName: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFileName, options, host, moduleResolutionCache, redirectedReference, resolverMode).resolvedModule!; // TODO: GH#18217
|
||||
actualResolveModuleNamesWorker = (moduleNames, containingFile, containingFileName, _reusedNames, redirectedReference) => loadWithModeAwareCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, containingFileName, redirectedReference, loader);
|
||||
}
|
||||
|
||||
let actualResolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference) => (ResolvedTypeReferenceDirective | undefined)[];
|
||||
let actualResolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference?: ResolvedProjectReference, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined) => (ResolvedTypeReferenceDirective | undefined)[];
|
||||
if (host.resolveTypeReferenceDirectives) {
|
||||
actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference) => host.resolveTypeReferenceDirectives!(Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options);
|
||||
actualResolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile, redirectedReference, containingFileMode) => host.resolveTypeReferenceDirectives!(Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options, containingFileMode);
|
||||
}
|
||||
else {
|
||||
typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache());
|
||||
const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(
|
||||
const loader = (typesRef: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined, resolutionMode: SourceFile["impliedNodeFormat"] | undefined) => resolveTypeReferenceDirective(
|
||||
typesRef,
|
||||
containingFile,
|
||||
options,
|
||||
host,
|
||||
redirectedReference,
|
||||
typeReferenceDirectiveResolutionCache,
|
||||
resolutionMode,
|
||||
).resolvedTypeReferenceDirective!; // TODO: GH#18217
|
||||
actualResolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference) => loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader);
|
||||
actualResolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile, redirectedReference, containingFileMode) => loadWithTypeDirectiveCache<ResolvedTypeReferenceDirective>(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader);
|
||||
}
|
||||
|
||||
// Map from a stringified PackageId to the source file with that id.
|
||||
@@ -917,6 +1103,7 @@ namespace ts {
|
||||
getSourceOfProjectReferenceRedirect,
|
||||
forEachResolvedProjectReference
|
||||
});
|
||||
const readFile = host.readFile.bind(host) as typeof host.readFile;
|
||||
|
||||
tracing?.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
|
||||
const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
|
||||
@@ -977,7 +1164,8 @@ namespace ts {
|
||||
const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile);
|
||||
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
|
||||
for (let i = 0; i < typeReferences.length; i++) {
|
||||
processTypeReferenceDirective(typeReferences[i], resolutions[i], { kind: FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: resolutions[i]?.packageId });
|
||||
// under node12/nodenext module resolution, load `types`/ata include names as cjs resolution results by passing an `undefined` mode
|
||||
processTypeReferenceDirective(typeReferences[i], /*mode*/ undefined, resolutions[i], { kind: FileIncludeKind.AutomaticTypeDirectiveFile, typeReference: typeReferences[i], packageId: resolutions[i]?.packageId });
|
||||
}
|
||||
tracing?.pop();
|
||||
}
|
||||
@@ -995,7 +1183,7 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
forEach(options.lib, (libFileName, index) => {
|
||||
processRootFile(combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: FileIncludeKind.LibFile, index });
|
||||
processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false, { kind: FileIncludeKind.LibFile, index });
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1101,6 +1289,7 @@ namespace ts {
|
||||
isSourceOfProjectReferenceRedirect,
|
||||
emitBuildInfo,
|
||||
fileExists,
|
||||
readFile,
|
||||
directoryExists,
|
||||
getSymlinkCache,
|
||||
realpath: host.realpath?.bind(host),
|
||||
@@ -1137,20 +1326,21 @@ namespace ts {
|
||||
const redirectedReference = getRedirectReferenceForResolution(containingFile);
|
||||
tracing?.push(tracing.Phase.Program, "resolveModuleNamesWorker", { containingFileName });
|
||||
performance.mark("beforeResolveModule");
|
||||
const result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference);
|
||||
const result = actualResolveModuleNamesWorker(moduleNames, containingFile, containingFileName, reusedNames, redirectedReference);
|
||||
performance.mark("afterResolveModule");
|
||||
performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
|
||||
tracing?.pop();
|
||||
return result;
|
||||
}
|
||||
|
||||
function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames: string[], containingFile: string | SourceFile): readonly (ResolvedTypeReferenceDirective | undefined)[] {
|
||||
function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames: string[] | readonly FileReference[], containingFile: string | SourceFile): readonly (ResolvedTypeReferenceDirective | undefined)[] {
|
||||
if (!typeDirectiveNames.length) return [];
|
||||
const containingFileName = !isString(containingFile) ? getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
|
||||
const redirectedReference = !isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
|
||||
const containingFileMode = !isString(containingFile) ? containingFile.impliedNodeFormat : undefined;
|
||||
tracing?.push(tracing.Phase.Program, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName });
|
||||
performance.mark("beforeResolveTypeReference");
|
||||
const result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
|
||||
const result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference, containingFileMode);
|
||||
performance.mark("afterResolveTypeReference");
|
||||
performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
|
||||
tracing?.pop();
|
||||
@@ -1159,7 +1349,7 @@ namespace ts {
|
||||
|
||||
function getRedirectReferenceForResolution(file: SourceFile) {
|
||||
const redirect = getResolvedProjectReferenceToRedirect(file.originalFileName);
|
||||
if (redirect || !fileExtensionIs(file.originalFileName, Extension.Dts)) return redirect;
|
||||
if (redirect || !fileExtensionIsOneOf(file.originalFileName, [Extension.Dts, Extension.Dcts, Extension.Dmts])) return redirect;
|
||||
|
||||
// The originalFileName could not be actual source file name if file found was d.ts from referecned project
|
||||
// So in this case try to look up if this is output from referenced project, if it is use the redirected project in that case
|
||||
@@ -1202,8 +1392,8 @@ namespace ts {
|
||||
return libs.length + 2;
|
||||
}
|
||||
|
||||
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined {
|
||||
return moduleResolutionCache && resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
|
||||
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string, mode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations | undefined {
|
||||
return moduleResolutionCache && resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache, mode);
|
||||
}
|
||||
|
||||
function toPath(fileName: string): Path {
|
||||
@@ -1256,8 +1446,10 @@ namespace ts {
|
||||
// Since we assume the filesystem does not change during program creation,
|
||||
// it is safe to reuse resolutions from the earlier call.
|
||||
const result: ResolvedModuleFull[] = [];
|
||||
let i = 0;
|
||||
for (const moduleName of moduleNames) {
|
||||
const resolvedModule = file.resolvedModules.get(moduleName)!;
|
||||
const resolvedModule = file.resolvedModules.get(moduleName, getModeForResolutionAtIndex(file, i))!;
|
||||
i++;
|
||||
result.push(resolvedModule);
|
||||
}
|
||||
return result;
|
||||
@@ -1287,7 +1479,7 @@ namespace ts {
|
||||
const moduleName = moduleNames[i];
|
||||
// If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
|
||||
if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
|
||||
const oldResolvedModule = getResolvedModule(oldSourceFile, moduleName);
|
||||
const oldResolvedModule = getResolvedModule(oldSourceFile, moduleName, getModeForResolutionAtIndex(oldSourceFile, i));
|
||||
if (oldResolvedModule) {
|
||||
if (isTraceEnabled(options, host)) {
|
||||
trace(host,
|
||||
@@ -1317,7 +1509,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
else {
|
||||
resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
|
||||
resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName, i);
|
||||
}
|
||||
|
||||
if (resolvesToAmbientModuleInNonModifiedFile) {
|
||||
@@ -1360,8 +1552,9 @@ namespace ts {
|
||||
|
||||
// If we change our policy of rechecking failed lookups on each program create,
|
||||
// we should adjust the value returned here.
|
||||
function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string): boolean {
|
||||
const resolutionToFile = getResolvedModule(oldSourceFile, moduleName);
|
||||
function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName: string, index: number): boolean {
|
||||
if (index >= length(oldSourceFile?.imports) + length(oldSourceFile?.moduleAugmentations)) return false; // mode index out of bounds, don't reuse resolution
|
||||
const resolutionToFile = getResolvedModule(oldSourceFile, moduleName, oldSourceFile && getModeForResolutionAtIndex(oldSourceFile, index));
|
||||
const resolvedFile = resolutionToFile && oldProgram!.getSourceFile(resolutionToFile.resolvedFileName);
|
||||
if (resolutionToFile && resolvedFile) {
|
||||
// In the old program, we resolved to an ambient module that was in the same
|
||||
@@ -1455,8 +1648,8 @@ namespace ts {
|
||||
|
||||
for (const oldSourceFile of oldSourceFiles) {
|
||||
let newSourceFile = host.getSourceFileByPath
|
||||
? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile)
|
||||
: host.getSourceFile(oldSourceFile.fileName, options.target!, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
|
||||
? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, getEmitScriptTarget(options), /*onError*/ undefined, shouldCreateNewSourceFile)
|
||||
: host.getSourceFile(oldSourceFile.fileName, getEmitScriptTarget(options), /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
|
||||
|
||||
if (!newSourceFile) {
|
||||
return StructureIsReused.Not;
|
||||
@@ -1491,6 +1684,7 @@ namespace ts {
|
||||
newSourceFile.originalFileName = oldSourceFile.originalFileName;
|
||||
newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
|
||||
newSourceFile.fileName = oldSourceFile.fileName;
|
||||
newSourceFile.impliedNodeFormat = oldSourceFile.impliedNodeFormat;
|
||||
|
||||
const packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
|
||||
if (packageName !== undefined) {
|
||||
@@ -1576,22 +1770,21 @@ namespace ts {
|
||||
const moduleNames = getModuleNames(newSourceFile);
|
||||
const resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile);
|
||||
// ensure that module resolution results are still correct
|
||||
const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo);
|
||||
const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, oldSourceFile, moduleResolutionIsEqualTo);
|
||||
if (resolutionsChanged) {
|
||||
structureIsReused = StructureIsReused.SafeModules;
|
||||
newSourceFile.resolvedModules = zipToMap(moduleNames, resolutions);
|
||||
newSourceFile.resolvedModules = zipToModeAwareCache(newSourceFile, moduleNames, resolutions);
|
||||
}
|
||||
else {
|
||||
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
|
||||
}
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, ref => toFileNameLowerCase(ref.fileName));
|
||||
const typesReferenceDirectives = newSourceFile.typeReferenceDirectives;
|
||||
const typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
|
||||
// ensure that types resolutions are still correct
|
||||
const typeReferenceEesolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo);
|
||||
if (typeReferenceEesolutionsChanged) {
|
||||
const typeReferenceResolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, oldSourceFile, typeDirectiveIsEqualTo);
|
||||
if (typeReferenceResolutionsChanged) {
|
||||
structureIsReused = StructureIsReused.SafeModules;
|
||||
newSourceFile.resolvedTypeReferenceDirectiveNames = zipToMap(typesReferenceDirectives, typeReferenceResolutions);
|
||||
newSourceFile.resolvedTypeReferenceDirectiveNames = zipToModeAwareCache(newSourceFile, typesReferenceDirectives, typeReferenceResolutions);
|
||||
}
|
||||
else {
|
||||
newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
|
||||
@@ -1737,7 +1930,7 @@ namespace ts {
|
||||
return equalityComparer(file.fileName, getDefaultLibraryFileName());
|
||||
}
|
||||
else {
|
||||
return some(options.lib, libFileName => equalityComparer(file.fileName, combinePaths(defaultLibraryPath, libFileName)));
|
||||
return some(options.lib, libFileName => equalityComparer(file.fileName, pathForLibFile(libFileName)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1918,15 +2111,25 @@ namespace ts {
|
||||
|
||||
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 = isPlainJsFile(sourceFile, options.checkJs);
|
||||
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;
|
||||
let checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : emptyArray;
|
||||
if (isPlainJs) {
|
||||
bindDiagnostics = filter(bindDiagnostics, d => plainJSErrors.has(d.code));
|
||||
checkDiagnostics = filter(checkDiagnostics, 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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2269,7 +2472,7 @@ namespace ts {
|
||||
|
||||
function createSyntheticImport(text: string, file: SourceFile) {
|
||||
const externalHelpersModuleReference = factory.createStringLiteral(text);
|
||||
const importDecl = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
|
||||
const importDecl = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference, /*assertClause*/ undefined);
|
||||
addEmitFlags(importDecl, EmitFlags.NeverApplyImportHelper);
|
||||
setParent(externalHelpersModuleReference, importDecl);
|
||||
setParent(importDecl, file);
|
||||
@@ -2328,6 +2531,7 @@ namespace ts {
|
||||
// An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
|
||||
// only through top - level external module names. Relative external module names are not permitted.
|
||||
if (moduleNameExpr && isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !isExternalModuleNameRelative(moduleNameExpr.text))) {
|
||||
setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
|
||||
imports = append(imports, moduleNameExpr);
|
||||
if (!usesUriStyleNodeCoreModules && currentNodeModulesDepth === 0 && !file.isDeclarationFile) {
|
||||
usesUriStyleNodeCoreModules = startsWith(moduleNameExpr.text, "node:");
|
||||
@@ -2336,6 +2540,7 @@ namespace ts {
|
||||
}
|
||||
else if (isModuleDeclaration(node)) {
|
||||
if (isAmbientModule(node) && (inAmbientModule || hasSyntacticModifier(node, ModifierFlags.Ambient) || file.isDeclarationFile)) {
|
||||
(node.name as Mutable<Node>).parent = node;
|
||||
const nameText = getTextOfIdentifierOrLiteral(node.name);
|
||||
// Ambient module declarations can be interpreted as augmentations for some existing external modules.
|
||||
// This will happen in two cases:
|
||||
@@ -2372,13 +2577,16 @@ namespace ts {
|
||||
while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
|
||||
const node = getNodeAtPosition(file, r.lastIndex);
|
||||
if (isJavaScriptFile && isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
|
||||
setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
|
||||
imports = append(imports, node.arguments[0]);
|
||||
}
|
||||
// we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
|
||||
else if (isImportCall(node) && node.arguments.length === 1 && isStringLiteralLike(node.arguments[0])) {
|
||||
// we have to check the argument list has length of at least 1. We will still have to process these even though we have parsing error.
|
||||
else if (isImportCall(node) && node.arguments.length >= 1 && isStringLiteralLike(node.arguments[0])) {
|
||||
setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
|
||||
imports = append(imports, node.arguments[0]);
|
||||
}
|
||||
else if (isLiteralImportTypeNode(node)) {
|
||||
setParentRecursive(node, /*incremental*/ false); // we need parent data on imports before the program is fully bound, so we ensure it's set here
|
||||
imports = append(imports, node.argument.literal);
|
||||
}
|
||||
}
|
||||
@@ -2406,7 +2614,7 @@ namespace ts {
|
||||
const libName = toFileNameLowerCase(ref.fileName);
|
||||
const libFileName = libMap.get(libName);
|
||||
if (libFileName) {
|
||||
return getSourceFile(combinePaths(defaultLibraryPath, libFileName));
|
||||
return getSourceFile(pathForLibFile(libFileName));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2423,13 +2631,13 @@ namespace ts {
|
||||
|
||||
if (hasExtension(fileName)) {
|
||||
const canonicalFileName = host.getCanonicalFileName(fileName);
|
||||
if (!options.allowNonTsExtensions && !forEach(supportedExtensionsWithJsonIfResolveJsonModule, extension => fileExtensionIs(canonicalFileName, extension))) {
|
||||
if (!options.allowNonTsExtensions && !forEach(flatten(supportedExtensionsWithJsonIfResolveJsonModule), extension => fileExtensionIs(canonicalFileName, extension))) {
|
||||
if (fail) {
|
||||
if (hasJSFileExtension(canonicalFileName)) {
|
||||
fail(Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
|
||||
}
|
||||
else {
|
||||
fail(Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
|
||||
fail(Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'");
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
@@ -2461,8 +2669,9 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sourceFileWithAddedExtension = forEach(supportedExtensions, extension => getSourceFile(fileName + extension));
|
||||
if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
|
||||
// Only try adding extensions from the first supported group (which should be .ts/.tsx/.d.ts)
|
||||
const sourceFileWithAddedExtension = forEach(supportedExtensions[0], extension => getSourceFile(fileName + extension));
|
||||
if (fail && !sourceFileWithAddedExtension) fail(Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + flatten(supportedExtensions).join("', '") + "'");
|
||||
return sourceFileWithAddedExtension;
|
||||
}
|
||||
}
|
||||
@@ -2616,7 +2825,7 @@ namespace ts {
|
||||
// We haven't looked for this file, do so now and cache result
|
||||
const file = host.getSourceFile(
|
||||
fileName,
|
||||
options.target!,
|
||||
getEmitScriptTarget(options),
|
||||
hostErrorMessage => addFilePreprocessingFileExplainingDiagnostic(/*file*/ undefined, reason, Diagnostics.Cannot_read_file_0_Colon_1, [fileName, hostErrorMessage]),
|
||||
shouldCreateNewSourceFile
|
||||
);
|
||||
@@ -2631,14 +2840,14 @@ namespace ts {
|
||||
redirectTargetsMap.add(fileFromPackageId.path, fileName);
|
||||
addFileToFilesByName(dupFile, path, redirectedPath);
|
||||
addFileIncludeReason(dupFile, reason);
|
||||
sourceFileToPackageName.set(path, packageId.name);
|
||||
sourceFileToPackageName.set(path, packageIdToPackageName(packageId));
|
||||
processingOtherFiles!.push(dupFile);
|
||||
return dupFile;
|
||||
}
|
||||
else if (file) {
|
||||
// This is the first source file to have this packageId.
|
||||
packageIdToSourceFile.set(packageIdKey, file);
|
||||
sourceFileToPackageName.set(path, packageId.name);
|
||||
sourceFileToPackageName.set(path, packageIdToPackageName(packageId));
|
||||
}
|
||||
}
|
||||
addFileToFilesByName(file, path, redirectedPath);
|
||||
@@ -2649,6 +2858,10 @@ namespace ts {
|
||||
file.path = path;
|
||||
file.resolvedPath = toPath(fileName);
|
||||
file.originalFileName = originalFileName;
|
||||
// It's a _little odd_ that we can't set `impliedNodeFormat` until the program step - but it's the first and only time we have a resolution cache
|
||||
// and a freshly made source file node on hand at the same time, and we need both to set the field. Persisting the resolution cache all the way
|
||||
// to the check and emit steps would be bad - so we much prefer detecting and storing the format information on the source file node upfront.
|
||||
file.impliedNodeFormat = getImpliedNodeFormatForFile(file.resolvedPath, moduleResolutionCache?.getPackageJsonInfoCache(), host, options);
|
||||
addFileIncludeReason(file, reason);
|
||||
|
||||
if (host.useCaseSensitiveFileNames()) {
|
||||
@@ -2800,8 +3013,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function processTypeReferenceDirectives(file: SourceFile) {
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const typeDirectives = map(file.typeReferenceDirectives, ref => toFileNameLowerCase(ref.fileName));
|
||||
const typeDirectives = file.typeReferenceDirectives;
|
||||
if (!typeDirectives) {
|
||||
return;
|
||||
}
|
||||
@@ -2813,28 +3025,34 @@ namespace ts {
|
||||
// store resolved type directive on the file
|
||||
const fileName = toFileNameLowerCase(ref.fileName);
|
||||
setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
|
||||
processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, { kind: FileIncludeKind.TypeReferenceDirective, file: file.path, index, });
|
||||
const mode = ref.resolutionMode || file.impliedNodeFormat;
|
||||
if (mode && getEmitModuleResolutionKind(options) !== ModuleResolutionKind.Node12 && getEmitModuleResolutionKind(options) !== ModuleResolutionKind.NodeNext) {
|
||||
programDiagnostics.add(createDiagnosticForRange(file, ref, Diagnostics.Resolution_modes_are_only_supported_when_moduleResolution_is_node12_or_nodenext));
|
||||
}
|
||||
processTypeReferenceDirective(fileName, mode, resolvedTypeReferenceDirective, { kind: FileIncludeKind.TypeReferenceDirective, file: file.path, index, });
|
||||
}
|
||||
}
|
||||
|
||||
function processTypeReferenceDirective(
|
||||
typeReferenceDirective: string,
|
||||
mode: SourceFile["impliedNodeFormat"] | undefined,
|
||||
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined,
|
||||
reason: FileIncludeReason
|
||||
): void {
|
||||
tracing?.push(tracing.Phase.Program, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: reason.kind, refPath: isReferencedFile(reason) ? reason.file : undefined });
|
||||
processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, reason);
|
||||
processTypeReferenceDirectiveWorker(typeReferenceDirective, mode, resolvedTypeReferenceDirective, reason);
|
||||
tracing?.pop();
|
||||
}
|
||||
|
||||
function processTypeReferenceDirectiveWorker(
|
||||
typeReferenceDirective: string,
|
||||
mode: SourceFile["impliedNodeFormat"] | undefined,
|
||||
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective | undefined,
|
||||
reason: FileIncludeReason
|
||||
): void {
|
||||
|
||||
// If we already found this library as a primary reference - nothing to do
|
||||
const previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
|
||||
const previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective, mode);
|
||||
if (previousResolution && previousResolution.primary) {
|
||||
return;
|
||||
}
|
||||
@@ -2879,17 +3097,36 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (saveResolution) {
|
||||
resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
|
||||
resolvedTypeReferenceDirectives.set(typeReferenceDirective, mode, resolvedTypeReferenceDirective);
|
||||
}
|
||||
}
|
||||
|
||||
function pathForLibFile(libFileName: string): string {
|
||||
// Support resolving to lib.dom.d.ts -> @typescript/lib-dom, and
|
||||
// lib.dom.iterable.d.ts -> @typescript/lib-dom/iterable
|
||||
// lib.es2015.symbol.wellknown.d.ts -> @typescript/lib-es2015/symbol-wellknown
|
||||
const components = libFileName.split(".");
|
||||
let path = components[1];
|
||||
let i = 2;
|
||||
while (components[i] && components[i] !== "d") {
|
||||
path += (i === 2 ? "/" : "-") + components[i];
|
||||
i++;
|
||||
}
|
||||
const resolveFrom = combinePaths(currentDirectory, `__lib_node_modules_lookup_${libFileName}__.ts`);
|
||||
const localOverrideModuleResult = resolveModuleName("@typescript/lib-" + path, resolveFrom, { moduleResolution: ModuleResolutionKind.NodeJs }, host, moduleResolutionCache);
|
||||
if (localOverrideModuleResult?.resolvedModule) {
|
||||
return localOverrideModuleResult.resolvedModule.resolvedFileName;
|
||||
}
|
||||
return combinePaths(defaultLibraryPath, libFileName);
|
||||
}
|
||||
|
||||
function processLibReferenceDirectives(file: SourceFile) {
|
||||
forEach(file.libReferenceDirectives, (libReference, index) => {
|
||||
const libName = toFileNameLowerCase(libReference.fileName);
|
||||
const libFileName = libMap.get(libName);
|
||||
if (libFileName) {
|
||||
// we ignore any 'no-default-lib' reference set on this file.
|
||||
processRootFile(combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: FileIncludeKind.LibReferenceDirective, file: file.path, index, });
|
||||
processRootFile(pathForLibFile(libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true, { kind: FileIncludeKind.LibReferenceDirective, file: file.path, index, });
|
||||
}
|
||||
else {
|
||||
const unqualifiedLibName = removeSuffix(removePrefix(libName, "lib."), ".d.ts");
|
||||
@@ -2919,7 +3156,7 @@ namespace ts {
|
||||
const optionsForFile = (useSourceOfProjectReferenceRedirect ? getRedirectReferenceForResolution(file)?.commandLine.options : undefined) || options;
|
||||
for (let index = 0; index < moduleNames.length; index++) {
|
||||
const resolution = resolutions[index];
|
||||
setResolvedModule(file, moduleNames[index], resolution);
|
||||
setResolvedModule(file, moduleNames[index], resolution, getModeForResolutionAtIndex(file, index));
|
||||
|
||||
if (!resolution) {
|
||||
continue;
|
||||
@@ -3045,6 +3282,21 @@ namespace ts {
|
||||
}
|
||||
|
||||
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")) {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
|
||||
}
|
||||
@@ -3181,7 +3433,7 @@ namespace ts {
|
||||
createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
|
||||
}
|
||||
|
||||
const languageVersion = options.target || ScriptTarget.ES3;
|
||||
const languageVersion = getEmitScriptTarget(options);
|
||||
|
||||
const firstNonAmbientExternalModuleSourceFile = find(files, f => isExternalModule(f) && !f.isDeclarationFile);
|
||||
if (options.isolatedModules) {
|
||||
@@ -3218,7 +3470,9 @@ namespace ts {
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
// Any emit other than common js, amd, es2015 or esnext is error
|
||||
@@ -3470,7 +3724,7 @@ namespace ts {
|
||||
message = Diagnostics.File_is_library_specified_here;
|
||||
break;
|
||||
}
|
||||
const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === options.target ? key : undefined);
|
||||
const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === getEmitScriptTarget(options) ? key : undefined);
|
||||
configFileNode = target ? getOptionsSyntaxByValue("target", target) : undefined;
|
||||
message = Diagnostics.File_is_default_library_for_target_specified_here;
|
||||
break;
|
||||
@@ -3579,8 +3833,8 @@ namespace ts {
|
||||
createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
|
||||
}
|
||||
|
||||
function createOptionValueDiagnostic(option1: string, message: DiagnosticMessage, arg0?: string) {
|
||||
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
|
||||
function createOptionValueDiagnostic(option1: string, message: DiagnosticMessage, arg0?: string, arg1?: string) {
|
||||
createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0, arg1);
|
||||
}
|
||||
|
||||
function createDiagnosticForReference(sourceFile: JsonSourceFile | undefined, index: number, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number) {
|
||||
@@ -3660,7 +3914,7 @@ namespace ts {
|
||||
return containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
|
||||
}
|
||||
|
||||
if (fileExtensionIsOneOf(filePath, supportedJSExtensions) || fileExtensionIs(filePath, Extension.Dts)) {
|
||||
if (fileExtensionIsOneOf(filePath, supportedJSExtensionsFlat) || fileExtensionIs(filePath, Extension.Dts)) {
|
||||
// Otherwise just check if sourceFile with the name exists
|
||||
const filePathWithoutExtension = removeFileExtension(filePath);
|
||||
return !!getSourceFileByPath((filePathWithoutExtension + Extension.Ts) as Path) ||
|
||||
@@ -4014,7 +4268,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function getModuleNameStringLiteralAt({ imports, moduleAugmentations }: SourceFile, index: number): StringLiteralLike {
|
||||
export function getModuleNameStringLiteralAt({ imports, moduleAugmentations }: SourceFileImportsList, index: number): StringLiteralLike {
|
||||
if (index < imports.length) return imports[index];
|
||||
let augIndex = imports.length;
|
||||
for (const aug of moduleAugmentations) {
|
||||
|
||||
@@ -5,9 +5,9 @@ namespace ts {
|
||||
startRecordingFilesWithChangedResolutions(): void;
|
||||
finishRecordingFilesWithChangedResolutions(): Path[] | undefined;
|
||||
|
||||
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[];
|
||||
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): CachedResolvedModuleWithFailedLookupLocations | undefined;
|
||||
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference, containingSourceFile?: SourceFile): (ResolvedModuleFull | undefined)[];
|
||||
getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): CachedResolvedModuleWithFailedLookupLocations | undefined;
|
||||
resolveTypeReferenceDirectives(typeDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference?: ResolvedProjectReference, containingFileMode?: SourceFile["impliedNodeFormat"]): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
|
||||
invalidateResolutionsOfFailedLookupLocations(): boolean;
|
||||
invalidateResolutionOfFile(filePath: Path): void;
|
||||
@@ -66,6 +66,7 @@ namespace ts {
|
||||
getCurrentProgram(): Program | undefined;
|
||||
fileIsOpen(filePath: Path): boolean;
|
||||
getCompilerHost?(): CompilerHost | undefined;
|
||||
onDiscoveredSymlink?(): void;
|
||||
}
|
||||
|
||||
interface DirectoryWatchesOfFailedLookup {
|
||||
@@ -166,8 +167,8 @@ namespace ts {
|
||||
// The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
|
||||
// The key in the map is source file's path.
|
||||
// The values are Map of resolutions with key being name lookedup.
|
||||
const resolvedModuleNames = new Map<Path, ESMap<string, CachedResolvedModuleWithFailedLookupLocations>>();
|
||||
const perDirectoryResolvedModuleNames: CacheWithRedirects<ESMap<string, CachedResolvedModuleWithFailedLookupLocations>> = createCacheWithRedirects();
|
||||
const resolvedModuleNames = new Map<Path, ModeAwareCache<CachedResolvedModuleWithFailedLookupLocations>>();
|
||||
const perDirectoryResolvedModuleNames: CacheWithRedirects<ModeAwareCache<CachedResolvedModuleWithFailedLookupLocations>> = createCacheWithRedirects();
|
||||
const nonRelativeModuleNameCache: CacheWithRedirects<PerModuleNameCache> = createCacheWithRedirects();
|
||||
const moduleResolutionCache = createModuleResolutionCache(
|
||||
getCurrentDirectory(),
|
||||
@@ -177,8 +178,8 @@ namespace ts {
|
||||
nonRelativeModuleNameCache,
|
||||
);
|
||||
|
||||
const resolvedTypeReferenceDirectives = new Map<Path, ESMap<string, CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations>>();
|
||||
const perDirectoryResolvedTypeReferenceDirectives: CacheWithRedirects<ESMap<string, CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations>> = createCacheWithRedirects();
|
||||
const resolvedTypeReferenceDirectives = new Map<Path, ModeAwareCache<CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations>>();
|
||||
const perDirectoryResolvedTypeReferenceDirectives: CacheWithRedirects<ModeAwareCache<CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations>> = createCacheWithRedirects();
|
||||
const typeReferenceDirectiveResolutionCache = createTypeReferenceDirectiveResolutionCache(
|
||||
getCurrentDirectory(),
|
||||
resolutionHost.getCanonicalFileName,
|
||||
@@ -314,8 +315,8 @@ namespace ts {
|
||||
hasChangedAutomaticTypeDirectiveNames = false;
|
||||
}
|
||||
|
||||
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): CachedResolvedModuleWithFailedLookupLocations {
|
||||
const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
|
||||
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, _containingSourceFile?: never, mode?: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): CachedResolvedModuleWithFailedLookupLocations {
|
||||
const primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference, mode);
|
||||
// return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
|
||||
if (!resolutionHost.getGlobalCache) {
|
||||
return primaryResult;
|
||||
@@ -346,35 +347,37 @@ namespace ts {
|
||||
return primaryResult;
|
||||
}
|
||||
|
||||
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference): CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations {
|
||||
return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache);
|
||||
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string | undefined, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, _containingSourceFile?: SourceFile, resolutionMode?: SourceFile["impliedNodeFormat"] | undefined): CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations {
|
||||
return ts.resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference, typeReferenceDirectiveResolutionCache, resolutionMode);
|
||||
}
|
||||
|
||||
interface ResolveNamesWithLocalCacheInput<T extends ResolutionWithFailedLookupLocations, R extends ResolutionWithResolvedFileName> {
|
||||
names: readonly string[];
|
||||
names: readonly string[] | readonly FileReference[];
|
||||
containingFile: string;
|
||||
redirectedReference: ResolvedProjectReference | undefined;
|
||||
cache: ESMap<Path, ESMap<string, T>>;
|
||||
perDirectoryCacheWithRedirects: CacheWithRedirects<ESMap<string, T>>;
|
||||
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference) => T;
|
||||
cache: ESMap<Path, ModeAwareCache<T>>;
|
||||
perDirectoryCacheWithRedirects: CacheWithRedirects<ModeAwareCache<T>>;
|
||||
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost, redirectedReference?: ResolvedProjectReference, containingSourceFile?: SourceFile, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext | undefined) => T;
|
||||
getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>;
|
||||
shouldRetryResolution: (t: T) => boolean;
|
||||
reusedNames?: readonly string[];
|
||||
logChanges?: boolean;
|
||||
containingSourceFile?: SourceFile;
|
||||
containingSourceFileMode?: SourceFile["impliedNodeFormat"];
|
||||
}
|
||||
function resolveNamesWithLocalCache<T extends ResolutionWithFailedLookupLocations, R extends ResolutionWithResolvedFileName>({
|
||||
names, containingFile, redirectedReference,
|
||||
cache, perDirectoryCacheWithRedirects,
|
||||
loader, getResolutionWithResolvedFileName,
|
||||
shouldRetryResolution, reusedNames, logChanges
|
||||
shouldRetryResolution, reusedNames, logChanges, containingSourceFile, containingSourceFileMode
|
||||
}: ResolveNamesWithLocalCacheInput<T, R>): (R | undefined)[] {
|
||||
const path = resolutionHost.toPath(containingFile);
|
||||
const resolutionsInFile = cache.get(path) || cache.set(path, new Map()).get(path)!;
|
||||
const resolutionsInFile = cache.get(path) || cache.set(path, createModeAwareCache()).get(path)!;
|
||||
const dirPath = getDirectoryPath(path);
|
||||
const perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
|
||||
let perDirectoryResolution = perDirectoryCache.get(dirPath);
|
||||
if (!perDirectoryResolution) {
|
||||
perDirectoryResolution = new Map();
|
||||
perDirectoryResolution = createModeAwareCache();
|
||||
perDirectoryCache.set(dirPath, perDirectoryResolution);
|
||||
}
|
||||
const resolvedModules: (R | undefined)[] = [];
|
||||
@@ -388,16 +391,26 @@ namespace ts {
|
||||
!redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
|
||||
!!redirectedReference;
|
||||
|
||||
const seenNamesInFile = new Map<string, true>();
|
||||
for (const name of names) {
|
||||
let resolution = resolutionsInFile.get(name);
|
||||
const seenNamesInFile = createModeAwareCache<true>();
|
||||
let i = 0;
|
||||
for (const entry of names) {
|
||||
const name = isString(entry) ? entry : entry.fileName.toLowerCase();
|
||||
// Imports supply a `containingSourceFile` but no `containingSourceFileMode` - it would be redundant
|
||||
// they require calculating the mode for a given import from it's position in the resolution table, since a given
|
||||
// import's syntax may override the file's default mode.
|
||||
// Type references instead supply a `containingSourceFileMode` and a non-string entry which contains
|
||||
// a default file mode override if applicable.
|
||||
const mode = !isString(entry) ? getModeForFileReference(entry, containingSourceFileMode) :
|
||||
containingSourceFile ? getModeForResolutionAtIndex(containingSourceFile, i) : undefined;
|
||||
i++;
|
||||
let resolution = resolutionsInFile.get(name, mode);
|
||||
// Resolution is valid if it is present and not invalidated
|
||||
if (!seenNamesInFile.has(name) &&
|
||||
if (!seenNamesInFile.has(name, mode) &&
|
||||
unmatchedRedirects || !resolution || resolution.isInvalidated ||
|
||||
// If the name is unresolved import that was invalidated, recalculate
|
||||
(hasInvalidatedNonRelativeUnresolvedImport && !isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
|
||||
const existingResolution = resolution;
|
||||
const resolutionInDirectory = perDirectoryResolution.get(name);
|
||||
const resolutionInDirectory = perDirectoryResolution.get(name, mode);
|
||||
if (resolutionInDirectory) {
|
||||
resolution = resolutionInDirectory;
|
||||
const host = resolutionHost.getCompilerHost?.() || resolutionHost;
|
||||
@@ -425,10 +438,13 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
else {
|
||||
resolution = loader(name, containingFile, compilerOptions, resolutionHost.getCompilerHost?.() || resolutionHost, redirectedReference);
|
||||
perDirectoryResolution.set(name, resolution);
|
||||
resolution = loader(name, containingFile, compilerOptions, resolutionHost.getCompilerHost?.() || resolutionHost, redirectedReference, containingSourceFile, mode);
|
||||
perDirectoryResolution.set(name, mode, resolution);
|
||||
if (resolutionHost.onDiscoveredSymlink && resolutionIsSymlink(resolution)) {
|
||||
resolutionHost.onDiscoveredSymlink();
|
||||
}
|
||||
}
|
||||
resolutionsInFile.set(name, resolution);
|
||||
resolutionsInFile.set(name, mode, resolution);
|
||||
watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
|
||||
if (existingResolution) {
|
||||
stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
|
||||
@@ -442,7 +458,7 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
const host = resolutionHost.getCompilerHost?.() || resolutionHost;
|
||||
if (isTraceEnabled(compilerOptions, host) && !seenNamesInFile.has(name)) {
|
||||
if (isTraceEnabled(compilerOptions, host) && !seenNamesInFile.has(name, mode)) {
|
||||
const resolved = getResolutionWithResolvedFileName(resolution);
|
||||
trace(
|
||||
host,
|
||||
@@ -465,15 +481,15 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
Debug.assert(resolution !== undefined && !resolution.isInvalidated);
|
||||
seenNamesInFile.set(name, true);
|
||||
seenNamesInFile.set(name, mode, true);
|
||||
resolvedModules.push(getResolutionWithResolvedFileName(resolution));
|
||||
}
|
||||
|
||||
// Stop watching and remove the unused name
|
||||
resolutionsInFile.forEach((resolution, name) => {
|
||||
if (!seenNamesInFile.has(name) && !contains(reusedNames, name)) {
|
||||
resolutionsInFile.forEach((resolution, name, mode) => {
|
||||
if (!seenNamesInFile.has(name, mode) && !contains(reusedNames, name)) {
|
||||
stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
|
||||
resolutionsInFile.delete(name);
|
||||
resolutionsInFile.delete(name, mode);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -498,7 +514,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string, redirectedReference?: ResolvedProjectReference): (ResolvedTypeReferenceDirective | undefined)[] {
|
||||
function resolveTypeReferenceDirectives(typeDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference?: ResolvedProjectReference, containingFileMode?: SourceFile["impliedNodeFormat"]): (ResolvedTypeReferenceDirective | undefined)[] {
|
||||
return resolveNamesWithLocalCache<CachedResolvedTypeReferenceDirectiveWithFailedLookupLocations, ResolvedTypeReferenceDirective>({
|
||||
names: typeDirectiveNames,
|
||||
containingFile,
|
||||
@@ -508,10 +524,11 @@ namespace ts {
|
||||
loader: resolveTypeReferenceDirective,
|
||||
getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
|
||||
shouldRetryResolution: resolution => resolution.resolvedTypeReferenceDirective === undefined,
|
||||
containingSourceFileMode: containingFileMode
|
||||
});
|
||||
}
|
||||
|
||||
function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference): (ResolvedModuleFull | undefined)[] {
|
||||
function resolveModuleNames(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference?: ResolvedProjectReference, containingSourceFile?: SourceFile): (ResolvedModuleFull | undefined)[] {
|
||||
return resolveNamesWithLocalCache<CachedResolvedModuleWithFailedLookupLocations, ResolvedModuleFull>({
|
||||
names: moduleNames,
|
||||
containingFile,
|
||||
@@ -523,12 +540,14 @@ namespace ts {
|
||||
shouldRetryResolution: resolution => !resolution.resolvedModule || !resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension),
|
||||
reusedNames,
|
||||
logChanges: logChangesWhenResolvingModule,
|
||||
containingSourceFile,
|
||||
});
|
||||
}
|
||||
|
||||
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): CachedResolvedModuleWithFailedLookupLocations | undefined {
|
||||
function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string, resolutionMode?: ModuleKind.CommonJS | ModuleKind.ESNext): CachedResolvedModuleWithFailedLookupLocations | undefined {
|
||||
const cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
|
||||
return cache && cache.get(moduleName);
|
||||
if (!cache) return undefined;
|
||||
return cache.get(moduleName, resolutionMode);
|
||||
}
|
||||
|
||||
function isNodeModulesAtTypesDirectory(dirPath: Path) {
|
||||
@@ -609,7 +628,7 @@ namespace ts {
|
||||
) {
|
||||
if (resolution.refCount) {
|
||||
resolution.refCount++;
|
||||
Debug.assertDefined(resolution.files);
|
||||
Debug.assertIsDefined(resolution.files);
|
||||
}
|
||||
else {
|
||||
resolution.refCount = 1;
|
||||
@@ -686,7 +705,7 @@ namespace ts {
|
||||
filePath: Path,
|
||||
getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>,
|
||||
) {
|
||||
unorderedRemoveItem(Debug.assertDefined(resolution.files), filePath);
|
||||
unorderedRemoveItem(Debug.checkDefined(resolution.files), filePath);
|
||||
resolution.refCount!--;
|
||||
if (resolution.refCount) {
|
||||
return;
|
||||
@@ -751,7 +770,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function removeResolutionsOfFileFromCache<T extends ResolutionWithFailedLookupLocations, R extends ResolutionWithResolvedFileName>(
|
||||
cache: ESMap<string, ESMap<string, T>>,
|
||||
cache: ESMap<string, ModeAwareCache<T>>,
|
||||
filePath: Path,
|
||||
getResolutionWithResolvedFileName: GetResolutionWithResolvedFileName<T, R>,
|
||||
) {
|
||||
@@ -788,7 +807,7 @@ namespace ts {
|
||||
for (const resolution of resolutions) {
|
||||
if (resolution.isInvalidated || !canInvalidate(resolution)) continue;
|
||||
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);
|
||||
// When its a file with inferred types resolution, invalidate type reference directive resolution
|
||||
hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || endsWith(containingFilePath, inferredTypesContainingFile);
|
||||
@@ -959,4 +978,11 @@ namespace ts {
|
||||
return dirPath === rootPath || canWatchDirectory(dirPath);
|
||||
}
|
||||
}
|
||||
|
||||
function resolutionIsSymlink(resolution: ResolutionWithFailedLookupLocations) {
|
||||
return !!(
|
||||
(resolution as ResolvedModuleWithFailedLookupLocations).resolvedModule?.originalPath ||
|
||||
(resolution as ResolvedTypeReferenceDirectiveWithFailedLookupLocations).resolvedTypeReferenceDirective?.originalPath
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,7 @@ namespace ts {
|
||||
any: SyntaxKind.AnyKeyword,
|
||||
as: SyntaxKind.AsKeyword,
|
||||
asserts: SyntaxKind.AssertsKeyword,
|
||||
assert: SyntaxKind.AssertKeyword,
|
||||
bigint: SyntaxKind.BigIntKeyword,
|
||||
boolean: SyntaxKind.BooleanKeyword,
|
||||
break: SyntaxKind.BreakKeyword,
|
||||
@@ -2373,6 +2374,7 @@ namespace ts {
|
||||
tokenValue = tokenValue.slice(0, -1);
|
||||
pos--;
|
||||
}
|
||||
return getIdentifierToken();
|
||||
}
|
||||
return token;
|
||||
}
|
||||
|
||||
@@ -322,7 +322,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
|
||||
const sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)$/;
|
||||
const sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\r?\n?$/;
|
||||
|
||||
const whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
|
||||
|
||||
export interface LineInfo {
|
||||
|
||||
+12
-4
@@ -499,12 +499,16 @@ namespace ts {
|
||||
/*@internal*/
|
||||
export const ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
|
||||
|
||||
let curSysLog: (s: string) => void = noop; // eslint-disable-line prefer-const
|
||||
|
||||
/*@internal*/
|
||||
export let sysLog: (s: string) => void = noop; // eslint-disable-line prefer-const
|
||||
export function sysLog(s: string) {
|
||||
return curSysLog(s);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export function setSysLog(logger: typeof sysLog) {
|
||||
sysLog = logger;
|
||||
curSysLog = logger;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
@@ -1625,7 +1629,6 @@ namespace ts {
|
||||
sysLog(`sysLog:: ${fileOrDirectory}:: Defaulting to fsWatchFile`);
|
||||
return watchPresentFileSystemEntryWithFsWatchFile();
|
||||
}
|
||||
|
||||
try {
|
||||
const presentWatcher = _fs.watch(
|
||||
fileOrDirectory,
|
||||
@@ -1804,7 +1807,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -1900,6 +1903,11 @@ namespace ts {
|
||||
return sys!;
|
||||
})();
|
||||
|
||||
/*@internal*/
|
||||
export function setSys(s: System) {
|
||||
sys = s;
|
||||
}
|
||||
|
||||
if (sys && sys.getEnvironmentVariable) {
|
||||
setCustomPollingValues(sys);
|
||||
Debug.setAssertionLevel(/^development$/i.test(sys.getEnvironmentVariable("NODE_ENV"))
|
||||
|
||||
@@ -341,4 +341,8 @@ namespace ts { // eslint-disable-line one-namespace-per-file
|
||||
// define after tracingEnabled is initialized
|
||||
export const startTracing = tracingEnabled.startTracing;
|
||||
export const dumpTracingLegend = tracingEnabled.dumpLegend;
|
||||
|
||||
export interface TracingNode {
|
||||
tracingPath?: Path;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,11 +3,15 @@ namespace ts {
|
||||
function getModuleTransformer(moduleKind: ModuleKind): TransformerFactory<SourceFile | Bundle> {
|
||||
switch (moduleKind) {
|
||||
case ModuleKind.ESNext:
|
||||
case ModuleKind.ES2022:
|
||||
case ModuleKind.ES2020:
|
||||
case ModuleKind.ES2015:
|
||||
return transformECMAScriptModule;
|
||||
case ModuleKind.System:
|
||||
return transformSystemModule;
|
||||
case ModuleKind.Node12:
|
||||
case ModuleKind.NodeNext:
|
||||
return transformNodeModule;
|
||||
default:
|
||||
return transformModule;
|
||||
}
|
||||
@@ -562,7 +566,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export const nullTransformationContext: TransformationContext = {
|
||||
factory,
|
||||
factory: factory, // eslint-disable-line object-shorthand
|
||||
getCompilerOptions: () => ({}),
|
||||
getEmitResolver: notImplemented,
|
||||
getEmitHost: notImplemented,
|
||||
|
||||
@@ -133,12 +133,15 @@ namespace ts {
|
||||
const languageVersion = getEmitScriptTarget(compilerOptions);
|
||||
const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
|
||||
|
||||
const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < ScriptTarget.ESNext;
|
||||
const shouldTransformPrivateElementsOrClassStaticBlocks = languageVersion < ScriptTarget.ES2022;
|
||||
|
||||
// We need to transform `this` in a static initializer into a reference to the class
|
||||
// when targeting < ES2022 since the assignment will be moved outside of the class body.
|
||||
const shouldTransformThisInStaticInitializers = languageVersion < ScriptTarget.ES2022;
|
||||
|
||||
// We don't need to transform `super` property access when targeting ES5, ES3 because
|
||||
// the es2015 transformation handles those.
|
||||
const shouldTransformSuperInStaticInitializers = (languageVersion <= ScriptTarget.ES2021 || !useDefineForClassFields) && languageVersion >= ScriptTarget.ES2015;
|
||||
const shouldTransformThisInStaticInitializers = languageVersion <= ScriptTarget.ES2021 || !useDefineForClassFields;
|
||||
const shouldTransformSuperInStaticInitializers = shouldTransformThisInStaticInitializers && languageVersion >= ScriptTarget.ES2015;
|
||||
|
||||
const previousOnSubstituteNode = context.onSubstituteNode;
|
||||
context.onSubstituteNode = onSubstituteNode;
|
||||
@@ -172,7 +175,7 @@ namespace ts {
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
const options = context.getCompilerOptions();
|
||||
if (node.isDeclarationFile
|
||||
|| useDefineForClassFields && options.target === ScriptTarget.ESNext) {
|
||||
|| useDefineForClassFields && getEmitScriptTarget(options) >= ScriptTarget.ES2022) {
|
||||
return node;
|
||||
}
|
||||
const visited = visitEachChild(node, visitor, context);
|
||||
@@ -266,15 +269,44 @@ namespace ts {
|
||||
|
||||
/**
|
||||
* If we visit a private name, this means it is an undeclared private name.
|
||||
* Replace it with an empty identifier to indicate a problem with the code.
|
||||
* Replace it with an empty identifier to indicate a problem with the code,
|
||||
* unless we are in a statement position - otherwise this will not trigger
|
||||
* a SyntaxError.
|
||||
*/
|
||||
function visitPrivateIdentifier(node: PrivateIdentifier) {
|
||||
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
|
||||
return node;
|
||||
}
|
||||
if (isStatement(node.parent)) {
|
||||
return node;
|
||||
}
|
||||
return setOriginalNode(factory.createIdentifier(""), node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits `#id in expr`
|
||||
*/
|
||||
function visitPrivateIdentifierInInExpression(node: BinaryExpression) {
|
||||
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
|
||||
return node;
|
||||
}
|
||||
const privId = node.left;
|
||||
Debug.assertNode(privId, isPrivateIdentifier);
|
||||
Debug.assert(node.operatorToken.kind === SyntaxKind.InKeyword);
|
||||
const info = accessPrivateIdentifier(privId);
|
||||
if (info) {
|
||||
const receiver = visitNode(node.right, visitor, isExpression);
|
||||
|
||||
return setOriginalNode(
|
||||
context.getEmitHelperFactory().createClassPrivateFieldInHelper(info.brandCheckIdentifier, receiver),
|
||||
node
|
||||
);
|
||||
}
|
||||
|
||||
// Private name has not been declared. Subsequent transformers will handle this error
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits the members of a class that has fields.
|
||||
*
|
||||
@@ -393,6 +425,11 @@ namespace ts {
|
||||
|
||||
if (isPrivateIdentifier(node.name)) {
|
||||
if (!shouldTransformPrivateElementsOrClassStaticBlocks) {
|
||||
if (isStatic(node)) {
|
||||
// static fields are left as is
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
// Initializer is elided as the field is initialized in transformConstructor.
|
||||
return factory.updatePropertyDeclaration(
|
||||
node,
|
||||
@@ -419,6 +456,28 @@ namespace ts {
|
||||
if (expr && !isSimpleInlineableExpression(expr)) {
|
||||
getPendingExpressions().push(expr);
|
||||
}
|
||||
|
||||
if (isStatic(node) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) {
|
||||
const initializerStatement = transformPropertyOrClassStaticBlock(node, factory.createThis());
|
||||
if (initializerStatement) {
|
||||
const staticBlock = factory.createClassStaticBlockDeclaration(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
factory.createBlock([initializerStatement])
|
||||
);
|
||||
|
||||
setOriginalNode(staticBlock, node);
|
||||
setCommentRange(staticBlock, node);
|
||||
|
||||
// Set the comment range for the statement to an empty synthetic range
|
||||
// and drop synthetic comments from the statement to avoid printing them twice.
|
||||
setCommentRange(initializerStatement, { pos: -1, end: -1 });
|
||||
setSyntheticLeadingComments(initializerStatement, undefined);
|
||||
setSyntheticTrailingComments(initializerStatement, undefined);
|
||||
return staticBlock;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -827,6 +886,9 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (node.operatorToken.kind === SyntaxKind.InKeyword && isPrivateIdentifier(node.left)) {
|
||||
return visitPrivateIdentifierInInExpression(node);
|
||||
}
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
@@ -974,8 +1036,6 @@ namespace ts {
|
||||
enableSubstitutionForClassStaticThisOrSuperReference();
|
||||
}
|
||||
|
||||
const staticProperties = getStaticPropertiesAndClassStaticBlock(node);
|
||||
|
||||
// If a class has private static fields, or a static field has a `this` or `super` reference,
|
||||
// then we need to allocate a temp variable to hold on to that reference.
|
||||
let pendingClassReferenceAssignment: BinaryExpression | undefined;
|
||||
@@ -1015,6 +1075,7 @@ namespace ts {
|
||||
// HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
|
||||
// a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
|
||||
|
||||
const staticProperties = getStaticPropertiesAndClassStaticBlock(node);
|
||||
if (some(staticProperties)) {
|
||||
addPropertyOrClassStaticBlockStatements(statements, staticProperties, factory.getInternalName(node));
|
||||
}
|
||||
@@ -1070,7 +1131,7 @@ namespace ts {
|
||||
transformClassMembers(node, isDerivedClass)
|
||||
);
|
||||
|
||||
const hasTransformableStatics = some(staticPropertiesOrClassStaticBlocks, p => isClassStaticBlockDeclaration(p) || !!p.initializer || (shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifier(p.name)));
|
||||
const hasTransformableStatics = shouldTransformPrivateElementsOrClassStaticBlocks && some(staticPropertiesOrClassStaticBlocks, p => isClassStaticBlockDeclaration(p) || !!p.initializer || isPrivateIdentifier(p.name));
|
||||
if (hasTransformableStatics || some(pendingExpressions)) {
|
||||
if (isDecoratedClassDeclaration) {
|
||||
Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
|
||||
@@ -1124,6 +1185,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function transformClassMembers(node: ClassDeclaration | ClassExpression, isDerivedClass: boolean) {
|
||||
const members: ClassElement[] = [];
|
||||
if (shouldTransformPrivateElementsOrClassStaticBlocks) {
|
||||
// Declare private names.
|
||||
for (const member of node.members) {
|
||||
@@ -1137,12 +1199,26 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
const members: ClassElement[] = [];
|
||||
const constructor = transformConstructor(node, isDerivedClass);
|
||||
const visitedMembers = visitNodes(node.members, classElementVisitor, isClassElement);
|
||||
|
||||
if (constructor) {
|
||||
members.push(constructor);
|
||||
}
|
||||
addRange(members, visitNodes(node.members, classElementVisitor, isClassElement));
|
||||
|
||||
if (!shouldTransformPrivateElementsOrClassStaticBlocks && some(pendingExpressions)) {
|
||||
members.push(factory.createClassStaticBlockDeclaration(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
factory.createBlock([
|
||||
factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))
|
||||
])
|
||||
));
|
||||
pendingExpressions = undefined;
|
||||
}
|
||||
|
||||
addRange(members, visitedMembers);
|
||||
|
||||
return setTextRange(factory.createNodeArray(members), /*location*/ node.members);
|
||||
}
|
||||
|
||||
@@ -1169,7 +1245,7 @@ namespace ts {
|
||||
if (useDefineForClassFields) {
|
||||
// If we are using define semantics and targeting ESNext or higher,
|
||||
// then we don't need to transform any class properties.
|
||||
return languageVersion < ScriptTarget.ESNext;
|
||||
return languageVersion < ScriptTarget.ES2022;
|
||||
}
|
||||
return isInitializedProperty(member) || shouldTransformPrivateElementsOrClassStaticBlocks && isPrivateIdentifierClassElementDeclaration(member);
|
||||
}
|
||||
@@ -1217,10 +1293,28 @@ namespace ts {
|
||||
|
||||
resumeLexicalEnvironment();
|
||||
|
||||
let indexOfFirstStatement = 0;
|
||||
const needsSyntheticConstructor = !constructor && isDerivedClass;
|
||||
let indexOfFirstStatementAfterSuper = 0;
|
||||
let prologueStatementCount = 0;
|
||||
let superStatementIndex = -1;
|
||||
let statements: Statement[] = [];
|
||||
|
||||
if (!constructor && isDerivedClass) {
|
||||
if (constructor?.body?.statements) {
|
||||
prologueStatementCount = factory.copyPrologue(constructor.body.statements, statements, /*ensureUseStrict*/ false, visitor);
|
||||
superStatementIndex = findSuperStatementIndex(constructor.body.statements, prologueStatementCount);
|
||||
|
||||
// If there was a super call, visit existing statements up to and including it
|
||||
if (superStatementIndex >= 0) {
|
||||
indexOfFirstStatementAfterSuper = superStatementIndex + 1;
|
||||
statements = [
|
||||
...statements.slice(0, prologueStatementCount),
|
||||
...visitNodes(constructor.body.statements, visitor, isStatement, prologueStatementCount, indexOfFirstStatementAfterSuper - prologueStatementCount),
|
||||
...statements.slice(prologueStatementCount),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
if (needsSyntheticConstructor) {
|
||||
// Add a synthetic `super` call:
|
||||
//
|
||||
// super(...arguments);
|
||||
@@ -1236,9 +1330,6 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
if (constructor) {
|
||||
indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
|
||||
}
|
||||
// Add the property initializers. Transforms this:
|
||||
//
|
||||
// public x = 1;
|
||||
@@ -1249,26 +1340,52 @@ namespace ts {
|
||||
// this.x = 1;
|
||||
// }
|
||||
//
|
||||
// If we do useDefineForClassFields, they'll be converted elsewhere.
|
||||
// We instead *remove* them from the transformed output at this stage.
|
||||
let parameterPropertyDeclarationCount = 0;
|
||||
if (constructor?.body) {
|
||||
let afterParameterProperties = findIndex(constructor.body.statements, s => !isParameterPropertyDeclaration(getOriginalNode(s), constructor), indexOfFirstStatement);
|
||||
if (afterParameterProperties === -1) {
|
||||
afterParameterProperties = constructor.body.statements.length;
|
||||
if (useDefineForClassFields) {
|
||||
statements = statements.filter(statement => !isParameterPropertyDeclaration(getOriginalNode(statement), constructor));
|
||||
}
|
||||
if (afterParameterProperties > indexOfFirstStatement) {
|
||||
if (!useDefineForClassFields) {
|
||||
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
|
||||
else {
|
||||
for (const statement of constructor.body.statements) {
|
||||
if (isParameterPropertyDeclaration(getOriginalNode(statement), constructor)) {
|
||||
parameterPropertyDeclarationCount++;
|
||||
}
|
||||
}
|
||||
if (parameterPropertyDeclarationCount > 0) {
|
||||
const parameterProperties = visitNodes(constructor.body.statements, visitor, isStatement, indexOfFirstStatementAfterSuper, parameterPropertyDeclarationCount);
|
||||
|
||||
// If there was a super() call found, add parameter properties immediately after it
|
||||
if (superStatementIndex >= 0) {
|
||||
addRange(statements, parameterProperties);
|
||||
}
|
||||
// If a synthetic super() call was added, add them just after it
|
||||
else if (needsSyntheticConstructor) {
|
||||
statements = [
|
||||
statements[0],
|
||||
...parameterProperties,
|
||||
...statements.slice(1),
|
||||
];
|
||||
}
|
||||
// Since there wasn't a super() call, add them to the top of the constructor
|
||||
else {
|
||||
statements = [...parameterProperties, ...statements];
|
||||
}
|
||||
|
||||
indexOfFirstStatementAfterSuper += parameterPropertyDeclarationCount;
|
||||
}
|
||||
indexOfFirstStatement = afterParameterProperties;
|
||||
}
|
||||
}
|
||||
|
||||
const receiver = factory.createThis();
|
||||
// private methods can be called in property initializers, they should execute first.
|
||||
addMethodStatements(statements, privateMethodsAndAccessors, receiver);
|
||||
addPropertyOrClassStaticBlockStatements(statements, properties, receiver);
|
||||
|
||||
// Add existing statements, skipping the initial super call.
|
||||
// Add existing statements after the initial prologues and super call
|
||||
if (constructor) {
|
||||
addRange(statements, visitNodes(constructor.body!.statements, visitor, isStatement, indexOfFirstStatement));
|
||||
addRange(statements, visitNodes(constructor.body!.statements, visitBodyStatement, isStatement, indexOfFirstStatementAfterSuper + prologueStatementCount));
|
||||
}
|
||||
|
||||
statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
|
||||
@@ -1283,6 +1400,14 @@ namespace ts {
|
||||
),
|
||||
/*location*/ constructor ? constructor.body : undefined
|
||||
);
|
||||
|
||||
function visitBodyStatement(statement: Node) {
|
||||
if (useDefineForClassFields && isParameterPropertyDeclaration(getOriginalNode(statement), constructor!)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return visitor(statement);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1293,20 +1418,41 @@ namespace ts {
|
||||
*/
|
||||
function addPropertyOrClassStaticBlockStatements(statements: Statement[], properties: readonly (PropertyDeclaration | ClassStaticBlockDeclaration)[], receiver: LeftHandSideExpression) {
|
||||
for (const property of properties) {
|
||||
const expression = isClassStaticBlockDeclaration(property) ?
|
||||
transformClassStaticBlockDeclaration(property) :
|
||||
transformProperty(property, receiver);
|
||||
if (!expression) {
|
||||
if (isStatic(property) && !shouldTransformPrivateElementsOrClassStaticBlocks && !useDefineForClassFields) {
|
||||
continue;
|
||||
}
|
||||
const statement = factory.createExpressionStatement(expression);
|
||||
setSourceMapRange(statement, moveRangePastModifiers(property));
|
||||
setCommentRange(statement, property);
|
||||
setOriginalNode(statement, property);
|
||||
|
||||
const statement = transformPropertyOrClassStaticBlock(property, receiver);
|
||||
if (!statement) {
|
||||
continue;
|
||||
}
|
||||
|
||||
statements.push(statement);
|
||||
}
|
||||
}
|
||||
|
||||
function transformPropertyOrClassStaticBlock(property: PropertyDeclaration | ClassStaticBlockDeclaration, receiver: LeftHandSideExpression) {
|
||||
const expression = isClassStaticBlockDeclaration(property) ?
|
||||
transformClassStaticBlockDeclaration(property) :
|
||||
transformProperty(property, receiver);
|
||||
if (!expression) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const statement = factory.createExpressionStatement(expression);
|
||||
setSourceMapRange(statement, moveRangePastModifiers(property));
|
||||
setCommentRange(statement, property);
|
||||
setOriginalNode(statement, property);
|
||||
|
||||
// `setOriginalNode` *copies* the `emitNode` from `property`, so now both
|
||||
// `statement` and `expression` have a copy of the synthesized comments.
|
||||
// Drop the comments from expression to avoid printing them twice.
|
||||
setSyntheticLeadingComments(expression, undefined);
|
||||
setSyntheticTrailingComments(expression, undefined);
|
||||
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates assignment expressions for property initializers.
|
||||
*
|
||||
|
||||
@@ -58,7 +58,7 @@ namespace ts {
|
||||
let needsScopeFixMarker = false;
|
||||
let resultHasScopeMarker = false;
|
||||
let enclosingDeclaration: Node;
|
||||
let necessaryTypeReferences: Set<string> | undefined;
|
||||
let necessaryTypeReferences: Set<[specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]> | undefined;
|
||||
let lateMarkedStatements: LateVisibilityPaintedStatement[] | undefined;
|
||||
let lateStatementReplacementMap: ESMap<NodeId, VisitResult<LateVisibilityPaintedStatement | ExportAssignment>>;
|
||||
let suppressNewDiagnosticContexts: boolean;
|
||||
@@ -92,7 +92,7 @@ namespace ts {
|
||||
const { noResolve, stripInternal } = options;
|
||||
return transformRoot;
|
||||
|
||||
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: readonly string[] | undefined): void {
|
||||
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: readonly [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined): void {
|
||||
if (!typeReferenceDirectives) {
|
||||
return;
|
||||
}
|
||||
@@ -296,7 +296,7 @@ namespace ts {
|
||||
const sourceFile = createUnparsedSourceFile(prepend, "dts", stripInternal);
|
||||
hasNoDefaultLib = hasNoDefaultLib || !!sourceFile.hasNoDefaultLib;
|
||||
collectReferences(sourceFile, refs);
|
||||
recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
|
||||
recordTypeReferenceDirectivesIfNecessary(map(sourceFile.typeReferenceDirectives, ref => [ref.fileName, ref.resolutionMode]));
|
||||
collectLibs(sourceFile, libs);
|
||||
return sourceFile;
|
||||
}
|
||||
@@ -354,10 +354,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getFileReferencesForUsedTypeReferences() {
|
||||
return necessaryTypeReferences ? mapDefined(arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
|
||||
return necessaryTypeReferences ? mapDefined(arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForSpecifierModeTuple) : [];
|
||||
}
|
||||
|
||||
function getFileReferenceForTypeName(typeName: string): FileReference | undefined {
|
||||
function getFileReferenceForSpecifierModeTuple([typeName, mode]: [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined]): FileReference | undefined {
|
||||
// Elide type references for which we have imports
|
||||
if (emittedImports) {
|
||||
for (const importStatement of emittedImports) {
|
||||
@@ -372,7 +372,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
}
|
||||
return { fileName: typeName, pos: -1, end: -1 };
|
||||
return { fileName: typeName, pos: -1, end: -1, ...(mode ? { resolutionMode: mode } : undefined) };
|
||||
}
|
||||
|
||||
function mapReferencesIntoArray(references: FileReference[], outputFilePath: string): (file: SourceFile) => void {
|
||||
@@ -399,7 +399,7 @@ namespace ts {
|
||||
// If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
|
||||
// via a non-relative name, emit a type reference directive to that non-relative name, rather than
|
||||
// a relative path to the declaration file
|
||||
recordTypeReferenceDirectivesIfNecessary([specifier]);
|
||||
recordTypeReferenceDirectivesIfNecessary([[specifier, /*mode*/ undefined]]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -732,7 +732,8 @@ namespace ts {
|
||||
/*decorators*/ undefined,
|
||||
decl.modifiers,
|
||||
decl.importClause,
|
||||
rewriteModuleSpecifier(decl, decl.moduleSpecifier)
|
||||
rewriteModuleSpecifier(decl, decl.moduleSpecifier),
|
||||
/*assertClause*/ undefined
|
||||
);
|
||||
}
|
||||
// The `importClause` visibility corresponds to the default's visibility.
|
||||
@@ -744,7 +745,7 @@ namespace ts {
|
||||
decl.importClause.isTypeOnly,
|
||||
visibleDefaultBinding,
|
||||
/*namedBindings*/ undefined,
|
||||
), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
|
||||
), rewriteModuleSpecifier(decl, decl.moduleSpecifier), /*assertClause*/ undefined);
|
||||
}
|
||||
if (decl.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) {
|
||||
// Namespace import (optionally with visible default)
|
||||
@@ -754,7 +755,7 @@ namespace ts {
|
||||
decl.importClause.isTypeOnly,
|
||||
visibleDefaultBinding,
|
||||
namedBindings,
|
||||
), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
|
||||
), rewriteModuleSpecifier(decl, decl.moduleSpecifier), /*assertClause*/ undefined) : undefined;
|
||||
}
|
||||
// Named imports (optionally with visible default)
|
||||
const bindingList = mapDefined(decl.importClause.namedBindings.elements, b => resolver.isDeclarationVisible(b) ? b : undefined);
|
||||
@@ -769,7 +770,8 @@ namespace ts {
|
||||
visibleDefaultBinding,
|
||||
bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined,
|
||||
),
|
||||
rewriteModuleSpecifier(decl, decl.moduleSpecifier)
|
||||
rewriteModuleSpecifier(decl, decl.moduleSpecifier),
|
||||
/*assertClause*/ undefined
|
||||
);
|
||||
}
|
||||
// Augmentation of export depends on import
|
||||
@@ -779,7 +781,8 @@ namespace ts {
|
||||
/*decorators*/ undefined,
|
||||
decl.modifiers,
|
||||
/*importClause*/ undefined,
|
||||
rewriteModuleSpecifier(decl, decl.moduleSpecifier)
|
||||
rewriteModuleSpecifier(decl, decl.moduleSpecifier),
|
||||
/*assertClause*/ undefined
|
||||
);
|
||||
}
|
||||
// Nothing visible
|
||||
@@ -875,7 +878,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
|
||||
getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input as DeclarationDiagnosticProducing);
|
||||
getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input);
|
||||
}
|
||||
|
||||
if (isTypeQueryNode(input)) {
|
||||
@@ -1070,7 +1073,7 @@ namespace ts {
|
||||
|
||||
function cleanup<T extends Node>(returnValue: T | undefined): T | undefined {
|
||||
if (returnValue && canProduceDiagnostic && hasDynamicName(input as Declaration)) {
|
||||
checkName(input as DeclarationDiagnosticProducing);
|
||||
checkName(input);
|
||||
}
|
||||
if (isEnclosingDeclaration(input)) {
|
||||
enclosingDeclaration = previousEnclosingDeclaration;
|
||||
@@ -1114,6 +1117,7 @@ namespace ts {
|
||||
input.isTypeOnly,
|
||||
input.exportClause,
|
||||
rewriteModuleSpecifier(input, input.moduleSpecifier),
|
||||
/*assertClause*/ undefined
|
||||
);
|
||||
}
|
||||
case SyntaxKind.ExportAssignment: {
|
||||
@@ -1252,7 +1256,7 @@ namespace ts {
|
||||
/*modifiers*/ undefined,
|
||||
/*isTypeOnly*/ false,
|
||||
factory.createNamedExports(map(exportMappings, ([gen, exp]) => {
|
||||
return factory.createExportSpecifier(gen, exp);
|
||||
return factory.createExportSpecifier(/*isTypeOnly*/ false, gen, exp);
|
||||
}))
|
||||
));
|
||||
}
|
||||
@@ -1606,7 +1610,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Elide "public" modifier, as it is the default
|
||||
function maskModifiers(node: Node, modifierMask?: ModifierFlags, modifierAdditions?: ModifierFlags): Modifier[] {
|
||||
function maskModifiers(node: Node, modifierMask?: ModifierFlags, modifierAdditions?: ModifierFlags): Modifier[] | undefined {
|
||||
return factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
|
||||
}
|
||||
|
||||
|
||||
+105
-106
@@ -1017,40 +1017,44 @@ namespace ts {
|
||||
const statements: Statement[] = [];
|
||||
resumeLexicalEnvironment();
|
||||
|
||||
// In derived classes, there may be code before the necessary super() call
|
||||
// We'll remove pre-super statements to be tacked on after the rest of the body
|
||||
const existingPrologue = takeWhile(constructor.body.statements, isPrologueDirective);
|
||||
const { superCall, superStatementIndex } = findSuperCallAndStatementIndex(constructor.body.statements, existingPrologue);
|
||||
const postSuperStatementsStart = superStatementIndex === -1 ? existingPrologue.length : superStatementIndex + 1;
|
||||
|
||||
// If a super call has already been synthesized,
|
||||
// we're going to assume that we should just transform everything after that.
|
||||
// The assumption is that no prior step in the pipeline has added any prologue directives.
|
||||
let statementOffset = 0;
|
||||
if (!hasSynthesizedSuper) statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false);
|
||||
addDefaultValueAssignmentsIfNeeded(statements, constructor);
|
||||
addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
|
||||
if (!hasSynthesizedSuper) statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor);
|
||||
let statementOffset = postSuperStatementsStart;
|
||||
if (!hasSynthesizedSuper) statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, statementOffset, /*ensureUseStrict*/ false);
|
||||
if (!hasSynthesizedSuper) statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor, /*filter*/ undefined);
|
||||
|
||||
// If the first statement is a call to `super()`, visit the statement directly
|
||||
// If there already exists a call to `super()`, visit the statement directly
|
||||
let superCallExpression: Expression | undefined;
|
||||
if (hasSynthesizedSuper) {
|
||||
superCallExpression = createDefaultSuperCallOrThis();
|
||||
}
|
||||
else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
|
||||
const firstStatement = constructor.body.statements[statementOffset];
|
||||
if (isExpressionStatement(firstStatement) && isSuperCall(firstStatement.expression)) {
|
||||
superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
|
||||
}
|
||||
else if (superCall) {
|
||||
superCallExpression = visitSuperCallInBody(superCall);
|
||||
}
|
||||
|
||||
if (superCallExpression) {
|
||||
hierarchyFacts |= HierarchyFacts.ConstructorWithCapturedSuper;
|
||||
statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
|
||||
}
|
||||
|
||||
// Add parameter defaults at the beginning of the output, with prologue statements
|
||||
addDefaultValueAssignmentsIfNeeded(prologue, constructor);
|
||||
addRestParameterIfNeeded(prologue, constructor, hasSynthesizedSuper);
|
||||
|
||||
// visit the remaining statements
|
||||
addRange(statements, visitNodes(constructor.body.statements, visitor, isStatement, /*start*/ statementOffset));
|
||||
|
||||
factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
|
||||
insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
|
||||
|
||||
if (isDerivedClass) {
|
||||
if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) {
|
||||
if (isDerivedClass || superCallExpression) {
|
||||
if (superCallExpression && postSuperStatementsStart === constructor.body.statements.length && !(constructor.body.transformFlags & TransformFlags.ContainsLexicalThis)) {
|
||||
// If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
|
||||
// following representation:
|
||||
//
|
||||
@@ -1099,9 +1103,19 @@ namespace ts {
|
||||
// })(Base);
|
||||
// ```
|
||||
|
||||
// Since the `super()` call was the first statement, we insert the `this` capturing call to
|
||||
// `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
|
||||
insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
|
||||
// If the super() call is the first statement, we can directly create and assign its result to `_this`
|
||||
if (superStatementIndex <= existingPrologue.length) {
|
||||
insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
|
||||
}
|
||||
// Since the `super()` call isn't the first statement, it's split across 1-2 statements:
|
||||
// * A prologue `var _this = this;`, in case the constructor accesses this before super()
|
||||
// * If it exists, a reassignment to that `_this` of the super() call
|
||||
else {
|
||||
insertCaptureThisForNode(prologue, constructor, createActualThis());
|
||||
if (superCallExpression) {
|
||||
insertSuperThisCaptureThisForNode(statements, superCallExpression);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
|
||||
statements.push(factory.createReturnStatement(factory.createUniqueName("_this", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel)));
|
||||
@@ -1126,19 +1140,41 @@ namespace ts {
|
||||
insertCaptureThisForNodeIfNeeded(prologue, constructor);
|
||||
}
|
||||
|
||||
const block = factory.createBlock(
|
||||
const body = factory.createBlock(
|
||||
setTextRange(
|
||||
factory.createNodeArray(
|
||||
concatenate(prologue, statements)
|
||||
[
|
||||
...existingPrologue,
|
||||
...prologue,
|
||||
...(superStatementIndex <= existingPrologue.length ? emptyArray : visitNodes(constructor.body.statements, visitor, isStatement, existingPrologue.length, superStatementIndex)),
|
||||
...statements
|
||||
]
|
||||
),
|
||||
/*location*/ constructor.body.statements
|
||||
),
|
||||
/*multiLine*/ true
|
||||
);
|
||||
|
||||
setTextRange(block, constructor.body);
|
||||
setTextRange(body, constructor.body);
|
||||
return body;
|
||||
}
|
||||
|
||||
return block;
|
||||
function findSuperCallAndStatementIndex(originalBodyStatements: NodeArray<Statement>, existingPrologue: Statement[]) {
|
||||
for (let i = existingPrologue.length; i < originalBodyStatements.length; i += 1) {
|
||||
const superCall = getSuperCallFromStatement(originalBodyStatements[i]);
|
||||
if (superCall) {
|
||||
// With a super() call, split the statements into pre-super() and 'body' (post-super())
|
||||
return {
|
||||
superCall,
|
||||
superStatementIndex: i,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Since there was no super() call found, consider all statements to be in the main 'body' (post-super())
|
||||
return {
|
||||
superStatementIndex: -1,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1511,6 +1547,25 @@ namespace ts {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assigns the `this` in a constructor to the result of its `super()` call.
|
||||
*
|
||||
* @param statements Statements in the constructor body.
|
||||
* @param superExpression Existing `super()` call for the constructor.
|
||||
*/
|
||||
function insertSuperThisCaptureThisForNode(statements: Statement[], superExpression: Expression): void {
|
||||
enableSubstitutionsForCapturedThis();
|
||||
const assignSuperExpression = factory.createExpressionStatement(
|
||||
factory.createBinaryExpression(
|
||||
factory.createThis(),
|
||||
SyntaxKind.EqualsToken,
|
||||
superExpression
|
||||
)
|
||||
);
|
||||
insertStatementAfterCustomPrologue(statements, assignSuperExpression);
|
||||
setCommentRange(assignSuperExpression, getOriginalNode(superExpression).parent);
|
||||
}
|
||||
|
||||
function insertCaptureThisForNode(statements: Statement[], node: Node, initializer: Expression | undefined): void {
|
||||
enableSubstitutionsForCapturedThis();
|
||||
const captureThisStatement = factory.createVariableStatement(
|
||||
@@ -1919,7 +1974,7 @@ namespace ts {
|
||||
if (isBlock(body)) {
|
||||
// ensureUseStrict is false because no new prologue-directive should be added.
|
||||
// addStandardPrologue will put already-existing directives at the beginning of the target statement-array
|
||||
statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false);
|
||||
statementOffset = factory.copyStandardPrologue(body.statements, prologue, 0, /*ensureUseStrict*/ false);
|
||||
statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedFunction);
|
||||
statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, isHoistedVariableStatement);
|
||||
}
|
||||
@@ -2899,9 +2954,11 @@ namespace ts {
|
||||
// variables declared in the loop initializer that will be changed inside the loop
|
||||
const loopOutParameters: LoopOutParameter[] = [];
|
||||
if (loopInitializer && (getCombinedNodeFlags(loopInitializer) & NodeFlags.BlockScoped)) {
|
||||
const hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
|
||||
const hasCapturedBindingsInForHead = shouldConvertInitializerOfForStatement(node) ||
|
||||
shouldConvertConditionOfForStatement(node) ||
|
||||
shouldConvertIncrementorOfForStatement(node);
|
||||
for (const decl of loopInitializer.declarations) {
|
||||
processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
|
||||
processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForHead);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3379,26 +3436,32 @@ namespace ts {
|
||||
});
|
||||
}
|
||||
|
||||
function processLoopVariableDeclaration(container: IterationStatement, decl: VariableDeclaration | BindingElement, loopParameters: ParameterDeclaration[], loopOutParameters: LoopOutParameter[], hasCapturedBindingsInForInitializer: boolean) {
|
||||
function processLoopVariableDeclaration(container: IterationStatement, decl: VariableDeclaration | BindingElement, loopParameters: ParameterDeclaration[], loopOutParameters: LoopOutParameter[], hasCapturedBindingsInForHead: boolean) {
|
||||
const name = decl.name;
|
||||
if (isBindingPattern(name)) {
|
||||
for (const element of name.elements) {
|
||||
if (!isOmittedExpression(element)) {
|
||||
processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
|
||||
processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForHead);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
|
||||
const checkFlags = resolver.getNodeCheckFlags(decl);
|
||||
if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter || hasCapturedBindingsInForInitializer) {
|
||||
if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter || hasCapturedBindingsInForHead) {
|
||||
const outParamName = factory.createUniqueName("out_" + idText(name));
|
||||
let flags: LoopOutParameterFlags = 0;
|
||||
if (checkFlags & NodeCheckFlags.NeedsLoopOutParameter) {
|
||||
flags |= LoopOutParameterFlags.Body;
|
||||
}
|
||||
if (isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
|
||||
flags |= LoopOutParameterFlags.Initializer;
|
||||
if (isForStatement(container)) {
|
||||
if (container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
|
||||
flags |= LoopOutParameterFlags.Initializer;
|
||||
}
|
||||
if (container.condition && resolver.isBindingCapturedByNode(container.condition, decl) ||
|
||||
container.incrementor && resolver.isBindingCapturedByNode(container.incrementor, decl)) {
|
||||
flags |= LoopOutParameterFlags.Body;
|
||||
}
|
||||
}
|
||||
loopOutParameters.push({ flags, originalName: name, outParamName });
|
||||
}
|
||||
@@ -3822,7 +3885,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
function visitImmediateSuperCallInBody(node: CallExpression) {
|
||||
function visitSuperCallInBody(node: CallExpression) {
|
||||
return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
|
||||
}
|
||||
|
||||
@@ -4102,86 +4165,22 @@ namespace ts {
|
||||
* @param node A TemplateExpression node.
|
||||
*/
|
||||
function visitTemplateExpression(node: TemplateExpression): Expression {
|
||||
const expressions: Expression[] = [];
|
||||
addTemplateHead(expressions, node);
|
||||
addTemplateSpans(expressions, node);
|
||||
|
||||
// createAdd will check if each expression binds less closely than binary '+'.
|
||||
// If it does, it wraps the expression in parentheses. Otherwise, something like
|
||||
// `abc${ 1 << 2 }`
|
||||
// becomes
|
||||
// "abc" + 1 << 2 + ""
|
||||
// which is really
|
||||
// ("abc" + 1) << (2 + "")
|
||||
// rather than
|
||||
// "abc" + (1 << 2) + ""
|
||||
const expression = reduceLeft(expressions, factory.createAdd)!;
|
||||
if (nodeIsSynthesized(expression)) {
|
||||
setTextRange(expression, node);
|
||||
}
|
||||
|
||||
return expression;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value indicating whether we need to include the head of a TemplateExpression.
|
||||
*
|
||||
* @param node A TemplateExpression node.
|
||||
*/
|
||||
function shouldAddTemplateHead(node: TemplateExpression) {
|
||||
// If this expression has an empty head literal and the first template span has a non-empty
|
||||
// literal, then emitting the empty head literal is not necessary.
|
||||
// `${ foo } and ${ bar }`
|
||||
// can be emitted as
|
||||
// foo + " and " + bar
|
||||
// This is because it is only required that one of the first two operands in the emit
|
||||
// output must be a string literal, so that the other operand and all following operands
|
||||
// are forced into strings.
|
||||
//
|
||||
// If the first template span has an empty literal, then the head must still be emitted.
|
||||
// `${ foo }${ bar }`
|
||||
// must still be emitted as
|
||||
// "" + foo + bar
|
||||
|
||||
// There is always atleast one templateSpan in this code path, since
|
||||
// NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
|
||||
Debug.assert(node.templateSpans.length !== 0);
|
||||
|
||||
return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the head of a TemplateExpression to an array of expressions.
|
||||
*
|
||||
* @param expressions An array of expressions.
|
||||
* @param node A TemplateExpression node.
|
||||
*/
|
||||
function addTemplateHead(expressions: Expression[], node: TemplateExpression): void {
|
||||
if (!shouldAddTemplateHead(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
expressions.push(factory.createStringLiteral(node.head.text));
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits and adds the template spans of a TemplateExpression to an array of expressions.
|
||||
*
|
||||
* @param expressions An array of expressions.
|
||||
* @param node A TemplateExpression node.
|
||||
*/
|
||||
function addTemplateSpans(expressions: Expression[], node: TemplateExpression): void {
|
||||
let expression: Expression = factory.createStringLiteral(node.head.text);
|
||||
for (const span of node.templateSpans) {
|
||||
expressions.push(visitNode(span.expression, visitor, isExpression));
|
||||
const args = [visitNode(span.expression, visitor, isExpression)];
|
||||
|
||||
// Only emit if the literal is non-empty.
|
||||
// The binary '+' operator is left-associative, so the first string concatenation
|
||||
// with the head will force the result up to this point to be a string.
|
||||
// Emitting a '+ ""' has no semantic effect for middles and tails.
|
||||
if (span.literal.text.length !== 0) {
|
||||
expressions.push(factory.createStringLiteral(span.literal.text));
|
||||
if (span.literal.text.length > 0) {
|
||||
args.push(factory.createStringLiteral(span.literal.text));
|
||||
}
|
||||
|
||||
expression = factory.createCallExpression(
|
||||
factory.createPropertyAccessExpression(expression, "concat"),
|
||||
/*typeArguments*/ undefined,
|
||||
args,
|
||||
);
|
||||
}
|
||||
|
||||
return setTextRange(expression, node);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -528,7 +528,7 @@ namespace ts {
|
||||
inHasLexicalThisContext(),
|
||||
hasLexicalArguments,
|
||||
promiseConstructor,
|
||||
transformAsyncFunctionBodyWorker(node.body!)
|
||||
transformAsyncFunctionBodyWorker(node.body)
|
||||
);
|
||||
|
||||
const declarations = endLexicalEnvironment();
|
||||
|
||||
@@ -59,6 +59,7 @@ namespace ts {
|
||||
let exportedVariableStatement = false;
|
||||
let enabledSubstitutions: ESNextSubstitutionFlags;
|
||||
let enclosingFunctionFlags: FunctionFlags;
|
||||
let parametersWithPrecedingObjectRestOrSpread: Set<ParameterDeclaration> | undefined;
|
||||
let enclosingSuperContainerFlags: NodeCheckFlags = 0;
|
||||
let hierarchyFacts: HierarchyFacts = 0;
|
||||
|
||||
@@ -282,7 +283,7 @@ namespace ts {
|
||||
function visitYieldExpression(node: YieldExpression) {
|
||||
if (enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator) {
|
||||
if (node.asteriskToken) {
|
||||
const expression = visitNode(Debug.assertDefined(node.expression), visitor, isExpression);
|
||||
const expression = visitNode(Debug.checkDefined(node.expression), visitor, isExpression);
|
||||
|
||||
return setOriginalNode(
|
||||
setTextRange(
|
||||
@@ -721,6 +722,7 @@ namespace ts {
|
||||
),
|
||||
EmitFlags.NoTokenTrailingSourceMaps
|
||||
);
|
||||
setOriginalNode(forStatement, node);
|
||||
|
||||
return factory.createTryStatement(
|
||||
factory.createBlock([
|
||||
@@ -785,7 +787,24 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
function parameterVisitor(node: Node) {
|
||||
Debug.assertNode(node, isParameter);
|
||||
return visitParameter(node);
|
||||
}
|
||||
|
||||
function visitParameter(node: ParameterDeclaration): ParameterDeclaration {
|
||||
if (parametersWithPrecedingObjectRestOrSpread?.has(node)) {
|
||||
return factory.updateParameterDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
node.dotDotDotToken,
|
||||
isBindingPattern(node.name) ? factory.getGeneratedNameForNode(node) : node.name,
|
||||
/*questionToken*/ undefined,
|
||||
/*type*/ undefined,
|
||||
/*initializer*/ undefined
|
||||
);
|
||||
}
|
||||
if (node.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
// Binding patterns are converted into a generated name and are
|
||||
// evaluated inside the function body.
|
||||
@@ -803,54 +822,78 @@ namespace ts {
|
||||
return visitEachChild(node, visitor, context);
|
||||
}
|
||||
|
||||
function collectParametersWithPrecedingObjectRestOrSpread(node: SignatureDeclaration) {
|
||||
let parameters: Set<ParameterDeclaration> | undefined;
|
||||
for (const parameter of node.parameters) {
|
||||
if (parameters) {
|
||||
parameters.add(parameter);
|
||||
}
|
||||
else if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
parameters = new Set();
|
||||
}
|
||||
}
|
||||
return parameters;
|
||||
}
|
||||
|
||||
function visitConstructorDeclaration(node: ConstructorDeclaration) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
enclosingFunctionFlags = FunctionFlags.Normal;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateConstructorDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
node.modifiers,
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
transformFunctionBody(node)
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function visitGetAccessorDeclaration(node: GetAccessorDeclaration) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
enclosingFunctionFlags = FunctionFlags.Normal;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateGetAccessorDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
node.modifiers,
|
||||
visitNode(node.name, visitor, isPropertyName),
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
/*type*/ undefined,
|
||||
transformFunctionBody(node)
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function visitSetAccessorDeclaration(node: SetAccessorDeclaration) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
enclosingFunctionFlags = FunctionFlags.Normal;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateSetAccessorDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
node.modifiers,
|
||||
visitNode(node.name, visitor, isPropertyName),
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
transformFunctionBody(node)
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function visitMethodDeclaration(node: MethodDeclaration) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateMethodDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
@@ -863,19 +906,22 @@ namespace ts {
|
||||
visitNode(node.name, visitor, isPropertyName),
|
||||
visitNode<Token<SyntaxKind.QuestionToken>>(/*questionToken*/ undefined, visitor, isToken),
|
||||
/*typeParameters*/ undefined,
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
/*type*/ undefined,
|
||||
enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator
|
||||
? transformAsyncGeneratorFunctionBody(node)
|
||||
: transformFunctionBody(node)
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function visitFunctionDeclaration(node: FunctionDeclaration) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateFunctionDeclaration(
|
||||
node,
|
||||
/*decorators*/ undefined,
|
||||
@@ -887,35 +933,41 @@ namespace ts {
|
||||
: node.asteriskToken,
|
||||
node.name,
|
||||
/*typeParameters*/ undefined,
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
/*type*/ undefined,
|
||||
enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator
|
||||
? transformAsyncGeneratorFunctionBody(node)
|
||||
: transformFunctionBody(node)
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function visitArrowFunction(node: ArrowFunction) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateArrowFunction(
|
||||
node,
|
||||
node.modifiers,
|
||||
/*typeParameters*/ undefined,
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
/*type*/ undefined,
|
||||
node.equalsGreaterThanToken,
|
||||
transformFunctionBody(node),
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
function visitFunctionExpression(node: FunctionExpression) {
|
||||
const savedEnclosingFunctionFlags = enclosingFunctionFlags;
|
||||
const savedParametersWithPrecedingObjectRestOrSpread = parametersWithPrecedingObjectRestOrSpread;
|
||||
enclosingFunctionFlags = getFunctionFlags(node);
|
||||
parametersWithPrecedingObjectRestOrSpread = collectParametersWithPrecedingObjectRestOrSpread(node);
|
||||
const updated = factory.updateFunctionExpression(
|
||||
node,
|
||||
enclosingFunctionFlags & FunctionFlags.Generator
|
||||
@@ -926,13 +978,14 @@ namespace ts {
|
||||
: node.asteriskToken,
|
||||
node.name,
|
||||
/*typeParameters*/ undefined,
|
||||
visitParameterList(node.parameters, visitor, context),
|
||||
visitParameterList(node.parameters, parameterVisitor, context),
|
||||
/*type*/ undefined,
|
||||
enclosingFunctionFlags & FunctionFlags.Async && enclosingFunctionFlags & FunctionFlags.Generator
|
||||
? transformAsyncGeneratorFunctionBody(node)
|
||||
: transformFunctionBody(node)
|
||||
);
|
||||
enclosingFunctionFlags = savedEnclosingFunctionFlags;
|
||||
parametersWithPrecedingObjectRestOrSpread = savedParametersWithPrecedingObjectRestOrSpread;
|
||||
return updated;
|
||||
}
|
||||
|
||||
@@ -1007,6 +1060,7 @@ namespace ts {
|
||||
statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
|
||||
}
|
||||
addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
|
||||
|
||||
const leadingStatements = endLexicalEnvironment();
|
||||
if (statementOffset > 0 || some(statements) || some(leadingStatements)) {
|
||||
const block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true);
|
||||
@@ -1018,25 +1072,86 @@ namespace ts {
|
||||
}
|
||||
|
||||
function appendObjectRestAssignmentsIfNeeded(statements: Statement[] | undefined, node: FunctionLikeDeclaration): Statement[] | undefined {
|
||||
let containsPrecedingObjectRestOrSpread = false;
|
||||
for (const parameter of node.parameters) {
|
||||
if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
const temp = factory.getGeneratedNameForNode(parameter);
|
||||
if (containsPrecedingObjectRestOrSpread) {
|
||||
if (isBindingPattern(parameter.name)) {
|
||||
// In cases where a binding pattern is simply '[]' or '{}',
|
||||
// we usually don't want to emit a var declaration; however, in the presence
|
||||
// of an initializer, we must emit that expression to preserve side effects.
|
||||
//
|
||||
// NOTE: see `insertDefaultValueAssignmentForBindingPattern` in es2015.ts
|
||||
if (parameter.name.elements.length > 0) {
|
||||
const declarations = flattenDestructuringBinding(
|
||||
parameter,
|
||||
visitor,
|
||||
context,
|
||||
FlattenLevel.All,
|
||||
factory.getGeneratedNameForNode(parameter));
|
||||
if (some(declarations)) {
|
||||
const declarationList = factory.createVariableDeclarationList(declarations);
|
||||
const statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList);
|
||||
setEmitFlags(statement, EmitFlags.CustomPrologue);
|
||||
statements = append(statements, statement);
|
||||
}
|
||||
}
|
||||
else if (parameter.initializer) {
|
||||
const name = factory.getGeneratedNameForNode(parameter);
|
||||
const initializer = visitNode(parameter.initializer, visitor, isExpression);
|
||||
const assignment = factory.createAssignment(name, initializer);
|
||||
const statement = factory.createExpressionStatement(assignment);
|
||||
setEmitFlags(statement, EmitFlags.CustomPrologue);
|
||||
statements = append(statements, statement);
|
||||
}
|
||||
}
|
||||
else if (parameter.initializer) {
|
||||
// Converts a parameter initializer into a function body statement, i.e.:
|
||||
//
|
||||
// function f(x = 1) { }
|
||||
//
|
||||
// becomes
|
||||
//
|
||||
// function f(x) {
|
||||
// if (typeof x === "undefined") { x = 1; }
|
||||
// }
|
||||
|
||||
const name = factory.cloneNode(parameter.name);
|
||||
setTextRange(name, parameter.name);
|
||||
setEmitFlags(name, EmitFlags.NoSourceMap);
|
||||
|
||||
const initializer = visitNode(parameter.initializer, visitor, isExpression);
|
||||
addEmitFlags(initializer, EmitFlags.NoSourceMap | EmitFlags.NoComments);
|
||||
|
||||
const assignment = factory.createAssignment(name, initializer);
|
||||
setTextRange(assignment, parameter);
|
||||
setEmitFlags(assignment, EmitFlags.NoComments);
|
||||
|
||||
const block = factory.createBlock([factory.createExpressionStatement(assignment)]);
|
||||
setTextRange(block, parameter);
|
||||
setEmitFlags(block, EmitFlags.SingleLine | EmitFlags.NoTrailingSourceMap | EmitFlags.NoTokenSourceMaps | EmitFlags.NoComments);
|
||||
|
||||
const typeCheck = factory.createTypeCheck(factory.cloneNode(parameter.name), "undefined");
|
||||
const statement = factory.createIfStatement(typeCheck, block);
|
||||
startOnNewLine(statement);
|
||||
setTextRange(statement, parameter);
|
||||
setEmitFlags(statement, EmitFlags.NoTokenSourceMaps | EmitFlags.NoTrailingSourceMap | EmitFlags.CustomPrologue | EmitFlags.NoComments);
|
||||
statements = append(statements, statement);
|
||||
}
|
||||
}
|
||||
else if (parameter.transformFlags & TransformFlags.ContainsObjectRestOrSpread) {
|
||||
containsPrecedingObjectRestOrSpread = true;
|
||||
const declarations = flattenDestructuringBinding(
|
||||
parameter,
|
||||
visitor,
|
||||
context,
|
||||
FlattenLevel.ObjectRest,
|
||||
temp,
|
||||
factory.getGeneratedNameForNode(parameter),
|
||||
/*doNotRecordTempVariablesInLine*/ false,
|
||||
/*skipInitializer*/ true,
|
||||
);
|
||||
if (some(declarations)) {
|
||||
const statement = factory.createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
factory.createVariableDeclarationList(
|
||||
declarations
|
||||
)
|
||||
);
|
||||
const declarationList = factory.createVariableDeclarationList(declarations);
|
||||
const statement = factory.createVariableStatement(/*modifiers*/ undefined, declarationList);
|
||||
setEmitFlags(statement, EmitFlags.CustomPrologue);
|
||||
statements = append(statements, statement);
|
||||
}
|
||||
|
||||
@@ -122,11 +122,11 @@ namespace ts {
|
||||
|
||||
function visitOptionalExpression(node: OptionalChain, captureThisArg: boolean, isDelete: boolean): Expression {
|
||||
const { expression, chain } = flattenChain(node);
|
||||
const left = visitNonOptionalExpression(expression, isCallChain(chain[0]), /*isDelete*/ false);
|
||||
const leftThisArg = isSyntheticReference(left) ? left.thisArg : undefined;
|
||||
let leftExpression = isSyntheticReference(left) ? left.expression : left;
|
||||
let capturedLeft: Expression = leftExpression;
|
||||
if (!isSimpleCopiableExpression(leftExpression)) {
|
||||
const left = visitNonOptionalExpression(skipPartiallyEmittedExpressions(expression), isCallChain(chain[0]), /*isDelete*/ false);
|
||||
let leftThisArg = isSyntheticReference(left) ? left.thisArg : undefined;
|
||||
let capturedLeft = isSyntheticReference(left) ? left.expression : left;
|
||||
let leftExpression = factory.restoreOuterExpressions(expression, capturedLeft, OuterExpressionKinds.PartiallyEmittedExpressions);
|
||||
if (!isSimpleCopiableExpression(capturedLeft)) {
|
||||
capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
|
||||
leftExpression = factory.createAssignment(capturedLeft, leftExpression);
|
||||
}
|
||||
@@ -152,6 +152,10 @@ namespace ts {
|
||||
break;
|
||||
case SyntaxKind.CallExpression:
|
||||
if (i === 0 && leftThisArg) {
|
||||
if (!isGeneratedIdentifier(leftThisArg)) {
|
||||
leftThisArg = factory.cloneNode(leftThisArg);
|
||||
addEmitFlags(leftThisArg, EmitFlags.NoComments);
|
||||
}
|
||||
rightExpression = factory.createFunctionCallCall(
|
||||
rightExpression,
|
||||
leftThisArg.kind === SyntaxKind.SuperKeyword ? factory.createThis() : leftThisArg,
|
||||
|
||||
@@ -26,12 +26,12 @@ namespace ts {
|
||||
return currentFileState.filenameDeclaration.name;
|
||||
}
|
||||
|
||||
function getJsxFactoryCalleePrimitive(childrenLength: number): "jsx" | "jsxs" | "jsxDEV" {
|
||||
return compilerOptions.jsx === JsxEmit.ReactJSXDev ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx";
|
||||
function getJsxFactoryCalleePrimitive(isStaticChildren: boolean): "jsx" | "jsxs" | "jsxDEV" {
|
||||
return compilerOptions.jsx === JsxEmit.ReactJSXDev ? "jsxDEV" : isStaticChildren ? "jsxs" : "jsx";
|
||||
}
|
||||
|
||||
function getJsxFactoryCallee(childrenLength: number) {
|
||||
const type = getJsxFactoryCalleePrimitive(childrenLength);
|
||||
function getJsxFactoryCallee(isStaticChildren: boolean) {
|
||||
const type = getJsxFactoryCalleePrimitive(isStaticChildren);
|
||||
return getImplicitImportForName(type);
|
||||
}
|
||||
|
||||
@@ -48,15 +48,15 @@ namespace ts {
|
||||
return existing.name;
|
||||
}
|
||||
if (!currentFileState.utilizedImplicitRuntimeImports) {
|
||||
currentFileState.utilizedImplicitRuntimeImports = createMap();
|
||||
currentFileState.utilizedImplicitRuntimeImports = new Map();
|
||||
}
|
||||
let specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
|
||||
if (!specifierSourceImports) {
|
||||
specifierSourceImports = createMap();
|
||||
specifierSourceImports = new Map();
|
||||
currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
|
||||
}
|
||||
const generatedName = factory.createUniqueName(`_${name}`, GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel | GeneratedIdentifierFlags.AllowNameSubstitution);
|
||||
const specifier = factory.createImportSpecifier(factory.createIdentifier(name), generatedName);
|
||||
const specifier = factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier(name), generatedName);
|
||||
generatedName.generatedImportReference = specifier;
|
||||
specifierSourceImports.set(name, specifier);
|
||||
return generatedName;
|
||||
@@ -85,7 +85,7 @@ namespace ts {
|
||||
for (const [importSource, importSpecifiersMap] of arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries())) {
|
||||
if (isExternalModule(node)) {
|
||||
// Add `import` statement
|
||||
const importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource));
|
||||
const importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource), /*assertClause*/ undefined);
|
||||
setParentRecursive(importStatement, /*incremental*/ false);
|
||||
statements = insertStatementAfterCustomPrologue(statements.slice(), importStatement);
|
||||
}
|
||||
@@ -200,69 +200,63 @@ namespace ts {
|
||||
}
|
||||
|
||||
function convertJsxChildrenToChildrenPropObject(children: readonly JsxChild[]) {
|
||||
const prop = convertJsxChildrenToChildrenPropAssignment(children);
|
||||
return prop && factory.createObjectLiteralExpression([prop]);
|
||||
}
|
||||
|
||||
function convertJsxChildrenToChildrenPropAssignment(children: readonly JsxChild[]) {
|
||||
const nonWhitespaceChildren = getSemanticJsxChildren(children);
|
||||
if (length(nonWhitespaceChildren) === 1) {
|
||||
if (length(nonWhitespaceChildren) === 1 && !(nonWhitespaceChildren[0] as JsxExpression).dotDotDotToken) {
|
||||
const result = transformJsxChildToExpression(nonWhitespaceChildren[0]);
|
||||
return result && factory.createObjectLiteralExpression([
|
||||
factory.createPropertyAssignment("children", result)
|
||||
]);
|
||||
return result && factory.createPropertyAssignment("children", result);
|
||||
}
|
||||
const result = mapDefined(children, transformJsxChildToExpression);
|
||||
return !result.length ? undefined : factory.createObjectLiteralExpression([
|
||||
factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result))
|
||||
]);
|
||||
return length(result) ? factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result)) : undefined;
|
||||
}
|
||||
|
||||
function visitJsxOpeningLikeElementJSX(node: JsxOpeningLikeElement, children: readonly JsxChild[] | undefined, isChild: boolean, location: TextRange) {
|
||||
const tagName = getTagName(node);
|
||||
let objectProperties: Expression;
|
||||
const childrenProp = children && children.length ? convertJsxChildrenToChildrenPropAssignment(children) : undefined;
|
||||
const keyAttr = find(node.attributes.properties, p => !!p.name && isIdentifier(p.name) && p.name.escapedText === "key") as JsxAttribute | undefined;
|
||||
const attrs = keyAttr ? filter(node.attributes.properties, p => p !== keyAttr) : node.attributes.properties;
|
||||
|
||||
let segments: Expression[] = [];
|
||||
if (attrs.length) {
|
||||
// Map spans of JsxAttribute nodes into object literals and spans
|
||||
// of JsxSpreadAttribute nodes into expressions.
|
||||
segments = flatten(
|
||||
spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread
|
||||
? map(attrs, transformJsxSpreadAttributeToExpression)
|
||||
: factory.createObjectLiteralExpression(map(attrs, transformJsxAttributeToObjectLiteralElement))
|
||||
)
|
||||
);
|
||||
|
||||
if (isJsxSpreadAttribute(attrs[0])) {
|
||||
// We must always emit at least one object literal before a spread
|
||||
// argument.factory.createObjectLiteral
|
||||
segments.unshift(factory.createObjectLiteralExpression());
|
||||
}
|
||||
}
|
||||
if (children && children.length) {
|
||||
const result = convertJsxChildrenToChildrenPropObject(children);
|
||||
if (result) {
|
||||
segments.push(result);
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.length === 0) {
|
||||
objectProperties = factory.createObjectLiteralExpression([]);
|
||||
// When there are no attributes, React wants {}
|
||||
}
|
||||
else {
|
||||
// Either emit one big object literal (no spread attribs), or
|
||||
// a call to the __assign helper.
|
||||
objectProperties = singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments);
|
||||
}
|
||||
|
||||
return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, length(getSemanticJsxChildren(children || emptyArray)), isChild, location);
|
||||
const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs, childrenProp) :
|
||||
factory.createObjectLiteralExpression(childrenProp ? [childrenProp] : emptyArray); // When there are no attributes, React wants {}
|
||||
return visitJsxOpeningLikeElementOrFragmentJSX(
|
||||
tagName,
|
||||
objectProperties,
|
||||
keyAttr,
|
||||
children || emptyArray,
|
||||
isChild,
|
||||
location
|
||||
);
|
||||
}
|
||||
|
||||
function visitJsxOpeningLikeElementOrFragmentJSX(tagName: Expression, objectProperties: Expression, keyAttr: JsxAttribute | undefined, childrenLength: number, isChild: boolean, location: TextRange) {
|
||||
const args: Expression[] = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)];
|
||||
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];
|
||||
// function jsx(type, config, maybeKey) {}
|
||||
// "maybeKey" is optional. It is acceptable to use "_jsx" without a third argument
|
||||
if (keyAttr) {
|
||||
args.push(transformJsxAttributeInitializer(keyAttr.initializer));
|
||||
}
|
||||
if (compilerOptions.jsx === JsxEmit.ReactJSXDev) {
|
||||
const originalFile = getOriginalNode(currentSourceFile);
|
||||
if (originalFile && isSourceFile(originalFile)) {
|
||||
// "maybeKey" has to be replaced with "void 0" to not break the jsxDEV signature
|
||||
if (keyAttr === undefined) {
|
||||
args.push(factory.createVoidZero());
|
||||
}
|
||||
// isStaticChildren development flag
|
||||
args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse());
|
||||
args.push(isStaticChildren ? factory.createTrue() : factory.createFalse());
|
||||
// __source development flag
|
||||
const lineCol = getLineAndCharacterOfPosition(originalFile, location.pos);
|
||||
args.push(factory.createObjectLiteralExpression([
|
||||
@@ -274,7 +268,11 @@ namespace ts {
|
||||
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) {
|
||||
startOnNewLine(element);
|
||||
@@ -285,47 +283,9 @@ namespace ts {
|
||||
|
||||
function visitJsxOpeningLikeElementCreateElement(node: JsxOpeningLikeElement, children: readonly JsxChild[] | undefined, isChild: boolean, location: TextRange) {
|
||||
const tagName = getTagName(node);
|
||||
let objectProperties: Expression | undefined;
|
||||
const attrs = node.attributes.properties;
|
||||
if (attrs.length === 0) {
|
||||
objectProperties = factory.createNull();
|
||||
// When there are no attributes, React wants "null"
|
||||
}
|
||||
else {
|
||||
const target = compilerOptions.target;
|
||||
if (target && target >= ScriptTarget.ES2018) {
|
||||
objectProperties = factory.createObjectLiteralExpression(
|
||||
flatten<SpreadAssignment | PropertyAssignment>(
|
||||
spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) =>
|
||||
isSpread ? map(attrs, transformJsxSpreadAttributeToSpreadAssignment) : map(attrs, transformJsxAttributeToObjectLiteralElement)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
else {
|
||||
// Map spans of JsxAttribute nodes into object literals and spans
|
||||
// of JsxSpreadAttribute nodes into expressions.
|
||||
const segments = flatten<Expression | ObjectLiteralExpression>(
|
||||
spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread
|
||||
? map(attrs, transformJsxSpreadAttributeToExpression)
|
||||
: factory.createObjectLiteralExpression(map(attrs, transformJsxAttributeToObjectLiteralElement))
|
||||
)
|
||||
);
|
||||
|
||||
if (isJsxSpreadAttribute(attrs[0])) {
|
||||
// We must always emit at least one object literal before a spread
|
||||
// argument.factory.createObjectLiteral
|
||||
segments.unshift(factory.createObjectLiteralExpression());
|
||||
}
|
||||
|
||||
// Either emit one big object literal (no spread attribs), or
|
||||
// a call to the __assign helper.
|
||||
objectProperties = singleOrUndefined(segments);
|
||||
if (!objectProperties) {
|
||||
objectProperties = emitHelpers().createAssignHelper(segments);
|
||||
}
|
||||
}
|
||||
}
|
||||
const objectProperties = length(attrs) ? transformJsxAttributesToObjectProps(attrs) :
|
||||
factory.createNull(); // When there are no attributes, React wants "null"
|
||||
|
||||
const callee = currentFileState.importSpecifier === undefined
|
||||
? createJsxFactoryExpression(
|
||||
@@ -364,7 +324,7 @@ namespace ts {
|
||||
getImplicitJsxFragmentReference(),
|
||||
childrenProps || factory.createObjectLiteralExpression([]),
|
||||
/*keyAttr*/ undefined,
|
||||
length(getSemanticJsxChildren(children)),
|
||||
children,
|
||||
isChild,
|
||||
location
|
||||
);
|
||||
@@ -392,6 +352,44 @@ namespace ts {
|
||||
return factory.createSpreadAssignment(visitNode(node.expression, visitor, isExpression));
|
||||
}
|
||||
|
||||
function transformJsxAttributesToObjectProps(attrs: readonly(JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) {
|
||||
const target = getEmitScriptTarget(compilerOptions);
|
||||
return target && target >= ScriptTarget.ES2018 ? factory.createObjectLiteralExpression(transformJsxAttributesToProps(attrs, children)) :
|
||||
transformJsxAttributesToExpression(attrs, children);
|
||||
}
|
||||
|
||||
function transformJsxAttributesToProps(attrs: readonly(JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) {
|
||||
const props = flatten<SpreadAssignment | PropertyAssignment>(spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) =>
|
||||
map(attrs, attr => isSpread ? transformJsxSpreadAttributeToSpreadAssignment(attr as JsxSpreadAttribute) : transformJsxAttributeToObjectLiteralElement(attr as JsxAttribute))));
|
||||
if (children) {
|
||||
props.push(children);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
function transformJsxAttributesToExpression(attrs: readonly(JsxSpreadAttribute | JsxAttribute)[], children?: PropertyAssignment) {
|
||||
// Map spans of JsxAttribute nodes into object literals and spans
|
||||
// of JsxSpreadAttribute nodes into expressions.
|
||||
const expressions = flatten(
|
||||
spanMap(attrs, isJsxSpreadAttribute, (attrs, isSpread) => isSpread
|
||||
? map(attrs, transformJsxSpreadAttributeToExpression)
|
||||
: factory.createObjectLiteralExpression(map(attrs, transformJsxAttributeToObjectLiteralElement))
|
||||
)
|
||||
);
|
||||
|
||||
if (isJsxSpreadAttribute(attrs[0])) {
|
||||
// We must always emit at least one object literal before a spread
|
||||
// argument.factory.createObjectLiteral
|
||||
expressions.unshift(factory.createObjectLiteralExpression());
|
||||
}
|
||||
|
||||
if (children) {
|
||||
expressions.push(factory.createObjectLiteralExpression([children]));
|
||||
}
|
||||
|
||||
return singleOrUndefined(expressions) || emitHelpers().createAssignHelper(expressions);
|
||||
}
|
||||
|
||||
function transformJsxSpreadAttributeToExpression(node: JsxSpreadAttribute) {
|
||||
return visitNode(node.expression, visitor, isExpression);
|
||||
}
|
||||
@@ -547,7 +545,8 @@ namespace ts {
|
||||
}
|
||||
|
||||
function visitJsxExpression(node: JsxExpression) {
|
||||
return visitNode(node.expression, visitor, isExpression);
|
||||
const expression = visitNode(node.expression, visitor, isExpression);
|
||||
return node.dotDotDotToken ? factory.createSpreadElement(expression!) : expression;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,10 @@ namespace ts {
|
||||
factory,
|
||||
getEmitHelperFactory: emitHelpers,
|
||||
} = context;
|
||||
const host = context.getEmitHost();
|
||||
const resolver = context.getEmitResolver();
|
||||
const compilerOptions = context.getCompilerOptions();
|
||||
const languageVersion = getEmitScriptTarget(compilerOptions);
|
||||
const previousOnEmitNode = context.onEmitNode;
|
||||
const previousOnSubstituteNode = context.onSubstituteNode;
|
||||
context.onEmitNode = onEmitNode;
|
||||
@@ -14,6 +17,8 @@ namespace ts {
|
||||
context.enableSubstitution(SyntaxKind.Identifier);
|
||||
|
||||
let helperNameSubstitutions: ESMap<string, Identifier> | undefined;
|
||||
let currentSourceFile: SourceFile | undefined;
|
||||
let importRequireStatements: [ImportDeclaration, VariableStatement] | undefined;
|
||||
return chainBundle(context, transformSourceFile);
|
||||
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
@@ -22,7 +27,16 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (isExternalModule(node) || compilerOptions.isolatedModules) {
|
||||
const result = updateExternalModule(node);
|
||||
currentSourceFile = node;
|
||||
importRequireStatements = undefined;
|
||||
let result = updateExternalModule(node);
|
||||
currentSourceFile = undefined;
|
||||
if (importRequireStatements) {
|
||||
result = factory.updateSourceFile(
|
||||
result,
|
||||
setTextRange(factory.createNodeArray(insertStatementsAfterCustomPrologue(result.statements.slice(), importRequireStatements)), result.statements),
|
||||
);
|
||||
}
|
||||
if (!isExternalModule(node) || some(result.statements, isExternalModuleIndicator)) {
|
||||
return result;
|
||||
}
|
||||
@@ -55,8 +69,10 @@ namespace ts {
|
||||
function visitor(node: Node): VisitResult<Node> {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ImportEqualsDeclaration:
|
||||
// Elide `import=` as it is not legal with --module ES6
|
||||
return undefined;
|
||||
// Though an error in es2020 modules, in node-flavor es2020 modules, we can helpfully transform this to a synthetic `require` call
|
||||
// To give easy access to a synchronous `require` in node-flavor esm. We do the transform even in scenarios where we error, but `import.meta.url`
|
||||
// is available, just because the output is reasonable for a node-like runtime.
|
||||
return getEmitScriptTarget(compilerOptions) >= ModuleKind.ES2020 ? visitImportEqualsDeclaration(node as ImportEqualsDeclaration) : undefined;
|
||||
case SyntaxKind.ExportAssignment:
|
||||
return visitExportAssignment(node as ExportAssignment);
|
||||
case SyntaxKind.ExportDeclaration:
|
||||
@@ -67,6 +83,106 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a `require()` call to import an external module.
|
||||
*
|
||||
* @param importNode The declaration to import.
|
||||
*/
|
||||
function createRequireCall(importNode: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration) {
|
||||
const moduleName = getExternalModuleNameLiteral(factory, importNode, Debug.checkDefined(currentSourceFile), host, resolver, compilerOptions);
|
||||
const args: Expression[] = [];
|
||||
if (moduleName) {
|
||||
args.push(moduleName);
|
||||
}
|
||||
|
||||
if (!importRequireStatements) {
|
||||
const createRequireName = factory.createUniqueName("_createRequire", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel);
|
||||
const importStatement = factory.createImportDeclaration(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
factory.createImportClause(
|
||||
/*isTypeOnly*/ false,
|
||||
/*name*/ undefined,
|
||||
factory.createNamedImports([
|
||||
factory.createImportSpecifier(/*isTypeOnly*/ false, factory.createIdentifier("createRequire"), createRequireName)
|
||||
])
|
||||
),
|
||||
factory.createStringLiteral("module")
|
||||
);
|
||||
const requireHelperName = factory.createUniqueName("__require", GeneratedIdentifierFlags.Optimistic | GeneratedIdentifierFlags.FileLevel);
|
||||
const requireStatement = factory.createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
factory.createVariableDeclarationList(
|
||||
[
|
||||
factory.createVariableDeclaration(
|
||||
requireHelperName,
|
||||
/*exclamationToken*/ undefined,
|
||||
/*type*/ undefined,
|
||||
factory.createCallExpression(factory.cloneNode(createRequireName), /*typeArguments*/ undefined, [
|
||||
factory.createPropertyAccessExpression(factory.createMetaProperty(SyntaxKind.ImportKeyword, factory.createIdentifier("meta")), factory.createIdentifier("url"))
|
||||
])
|
||||
)
|
||||
],
|
||||
/*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None
|
||||
)
|
||||
);
|
||||
importRequireStatements = [importStatement, requireStatement];
|
||||
|
||||
}
|
||||
|
||||
const name = importRequireStatements[1].declarationList.declarations[0].name;
|
||||
Debug.assertNode(name, isIdentifier);
|
||||
return factory.createCallExpression(factory.cloneNode(name), /*typeArguments*/ undefined, args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits an ImportEqualsDeclaration node.
|
||||
*
|
||||
* @param node The node to visit.
|
||||
*/
|
||||
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
|
||||
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
|
||||
|
||||
let statements: Statement[] | undefined;
|
||||
statements = append(statements,
|
||||
setOriginalNode(
|
||||
setTextRange(
|
||||
factory.createVariableStatement(
|
||||
/*modifiers*/ undefined,
|
||||
factory.createVariableDeclarationList(
|
||||
[
|
||||
factory.createVariableDeclaration(
|
||||
factory.cloneNode(node.name),
|
||||
/*exclamationToken*/ undefined,
|
||||
/*type*/ undefined,
|
||||
createRequireCall(node)
|
||||
)
|
||||
],
|
||||
/*flags*/ languageVersion >= ScriptTarget.ES2015 ? NodeFlags.Const : NodeFlags.None
|
||||
)
|
||||
),
|
||||
node),
|
||||
node
|
||||
)
|
||||
);
|
||||
|
||||
statements = appendExportsOfImportEqualsDeclaration(statements, node);
|
||||
|
||||
return singleOrMany(statements);
|
||||
}
|
||||
|
||||
function appendExportsOfImportEqualsDeclaration(statements: Statement[] | undefined, node: ImportEqualsDeclaration) {
|
||||
if (hasSyntacticModifier(node, ModifierFlags.Export)) {
|
||||
statements = append(statements, factory.createExportDeclaration(
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
node.isTypeOnly,
|
||||
factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, /*propertyName*/ undefined, idText(node.name))])
|
||||
));
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
function visitExportAssignment(node: ExportAssignment): VisitResult<ExportAssignment> {
|
||||
// Elide `export=` as it is not legal with --module ES6
|
||||
return node.isExportEquals ? undefined : node;
|
||||
@@ -96,6 +212,7 @@ namespace ts {
|
||||
)
|
||||
),
|
||||
node.moduleSpecifier,
|
||||
node.assertClause
|
||||
);
|
||||
setOriginalNode(importDecl, node.exportClause);
|
||||
|
||||
@@ -103,7 +220,7 @@ namespace ts {
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
/*isTypeOnly*/ false,
|
||||
factory.createNamedExports([factory.createExportSpecifier(synthName, oldIdentifier)]),
|
||||
factory.createNamedExports([factory.createExportSpecifier(/*isTypeOnly*/ false, synthName, oldIdentifier)]),
|
||||
);
|
||||
setOriginalNode(exportDecl, node);
|
||||
|
||||
|
||||
@@ -556,7 +556,7 @@ namespace ts {
|
||||
case SyntaxKind.PartiallyEmittedExpression:
|
||||
return visitPartiallyEmittedExpression(node as PartiallyEmittedExpression, valueIsDiscarded);
|
||||
case SyntaxKind.CallExpression:
|
||||
if (isImportCall(node)) {
|
||||
if (isImportCall(node) && currentSourceFile.impliedNodeFormat === undefined) {
|
||||
return visitImportCallExpression(node);
|
||||
}
|
||||
break;
|
||||
@@ -814,7 +814,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
const promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
|
||||
if (compilerOptions.esModuleInterop) {
|
||||
if (getESModuleInterop(compilerOptions)) {
|
||||
return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
|
||||
}
|
||||
return promise;
|
||||
@@ -828,7 +828,7 @@ namespace ts {
|
||||
// if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
|
||||
const promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
|
||||
let requireCall: Expression = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
|
||||
if (compilerOptions.esModuleInterop) {
|
||||
if (getESModuleInterop(compilerOptions)) {
|
||||
requireCall = emitHelpers().createImportStarHelper(requireCall);
|
||||
}
|
||||
|
||||
@@ -864,7 +864,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getHelperExpressionForExport(node: ExportDeclaration, innerExpr: Expression) {
|
||||
if (!compilerOptions.esModuleInterop || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
|
||||
if (!getESModuleInterop(compilerOptions) || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
|
||||
return innerExpr;
|
||||
}
|
||||
if (getExportNeedsImportStarHelper(node)) {
|
||||
@@ -874,7 +874,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function getHelperExpressionForImport(node: ImportDeclaration, innerExpr: Expression) {
|
||||
if (!compilerOptions.esModuleInterop || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
|
||||
if (!getESModuleInterop(compilerOptions) || getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) {
|
||||
return innerExpr;
|
||||
}
|
||||
if (getImportNeedsImportStarHelper(node)) {
|
||||
@@ -1134,7 +1134,7 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
const exportNeedsImportDefault =
|
||||
!!compilerOptions.esModuleInterop &&
|
||||
!!getESModuleInterop(compilerOptions) &&
|
||||
!(getEmitFlags(node) & EmitFlags.NeverApplyImportHelper) &&
|
||||
idText(specifier.propertyName || specifier.name) === "default";
|
||||
const exportedValue = factory.createPropertyAccessExpression(
|
||||
@@ -1853,7 +1853,7 @@ namespace ts {
|
||||
if (isIdentifier(node.expression)) {
|
||||
const expression = substituteExpressionIdentifier(node.expression);
|
||||
noSubstitution[getNodeId(expression)] = true;
|
||||
if (!isIdentifier(expression)) {
|
||||
if (!isIdentifier(expression) && !(getEmitFlags(node.expression) & EmitFlags.HelperName)) {
|
||||
return addEmitFlags(
|
||||
factory.updateCallExpression(node,
|
||||
expression,
|
||||
@@ -1872,7 +1872,7 @@ namespace ts {
|
||||
if (isIdentifier(node.tag)) {
|
||||
const tag = substituteExpressionIdentifier(node.tag);
|
||||
noSubstitution[getNodeId(tag)] = true;
|
||||
if (!isIdentifier(tag)) {
|
||||
if (!isIdentifier(tag) && !(getEmitFlags(node.tag) & EmitFlags.HelperName)) {
|
||||
return addEmitFlags(
|
||||
factory.updateTaggedTemplateExpression(node,
|
||||
tag,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
/*@internal*/
|
||||
namespace ts {
|
||||
export function transformNodeModule(context: TransformationContext) {
|
||||
const previousOnSubstituteNode = context.onSubstituteNode;
|
||||
const previousOnEmitNode = context.onEmitNode;
|
||||
|
||||
const esmTransform = transformECMAScriptModule(context);
|
||||
|
||||
const esmOnSubstituteNode = context.onSubstituteNode;
|
||||
const esmOnEmitNode = context.onEmitNode;
|
||||
|
||||
context.onSubstituteNode = previousOnSubstituteNode;
|
||||
context.onEmitNode = previousOnEmitNode;
|
||||
|
||||
const cjsTransform = transformModule(context);
|
||||
|
||||
const cjsOnSubstituteNode = context.onSubstituteNode;
|
||||
const cjsOnEmitNode = context.onEmitNode;
|
||||
|
||||
context.onSubstituteNode = onSubstituteNode;
|
||||
context.onEmitNode = onEmitNode;
|
||||
context.enableSubstitution(SyntaxKind.SourceFile);
|
||||
context.enableEmitNotification(SyntaxKind.SourceFile);
|
||||
|
||||
let currentSourceFile: SourceFile | undefined;
|
||||
return transformSourceFileOrBundle;
|
||||
|
||||
function onSubstituteNode(hint: EmitHint, node: Node) {
|
||||
if (isSourceFile(node)) {
|
||||
currentSourceFile = node;
|
||||
// Neither component transform wants substitution notifications for `SourceFile`s, and, in fact, relies on
|
||||
// the source file emit notification to setup scope variables for substitutions (so we _cannot_ call their substitute
|
||||
// functions on source files safely, as that context only gets setup in a later pipeline phase!)
|
||||
return previousOnSubstituteNode(hint, node);
|
||||
}
|
||||
else {
|
||||
if (!currentSourceFile) {
|
||||
return previousOnSubstituteNode(hint, node);
|
||||
}
|
||||
if (currentSourceFile.impliedNodeFormat === ModuleKind.ESNext) {
|
||||
return esmOnSubstituteNode(hint, node);
|
||||
}
|
||||
return cjsOnSubstituteNode(hint, node);
|
||||
}
|
||||
}
|
||||
|
||||
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
|
||||
if (isSourceFile(node)) {
|
||||
currentSourceFile = node;
|
||||
}
|
||||
if (!currentSourceFile) {
|
||||
return previousOnEmitNode(hint, node, emitCallback);
|
||||
}
|
||||
if (currentSourceFile.impliedNodeFormat === ModuleKind.ESNext) {
|
||||
return esmOnEmitNode(hint, node, emitCallback);
|
||||
}
|
||||
return cjsOnEmitNode(hint, node, emitCallback);
|
||||
}
|
||||
|
||||
function getModuleTransformForFile(file: SourceFile): (typeof esmTransform) {
|
||||
return file.impliedNodeFormat === ModuleKind.ESNext ? esmTransform : cjsTransform;
|
||||
}
|
||||
|
||||
function transformSourceFile(node: SourceFile) {
|
||||
if (node.isDeclarationFile) {
|
||||
return node;
|
||||
}
|
||||
|
||||
currentSourceFile = node;
|
||||
const result = getModuleTransformForFile(node)(node);
|
||||
currentSourceFile = undefined;
|
||||
Debug.assert(isSourceFile(result));
|
||||
return result;
|
||||
}
|
||||
|
||||
function transformSourceFileOrBundle(node: SourceFile | Bundle) {
|
||||
return node.kind === SyntaxKind.SourceFile ? transformSourceFile(node) : transformBundle(node);
|
||||
}
|
||||
|
||||
function transformBundle(node: Bundle) {
|
||||
return context.factory.createBundle(map(node.sourceFiles, transformSourceFile), node.prepends);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1189,7 +1189,7 @@ namespace ts {
|
||||
//
|
||||
|
||||
const prefix = getClassMemberPrefix(node, member);
|
||||
const memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
|
||||
const memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ !hasSyntacticModifier(member, ModifierFlags.Ambient));
|
||||
const descriptor = languageVersion > ScriptTarget.ES3
|
||||
? member.kind === SyntaxKind.PropertyDeclaration
|
||||
// We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
|
||||
@@ -1511,6 +1511,7 @@ namespace ts {
|
||||
case SyntaxKind.BooleanKeyword:
|
||||
return factory.createIdentifier("Boolean");
|
||||
|
||||
case SyntaxKind.TemplateLiteralType:
|
||||
case SyntaxKind.StringKeyword:
|
||||
return factory.createIdentifier("String");
|
||||
|
||||
@@ -1932,13 +1933,21 @@ namespace ts {
|
||||
}
|
||||
|
||||
let statements: Statement[] = [];
|
||||
let indexOfFirstStatement = 0;
|
||||
|
||||
resumeLexicalEnvironment();
|
||||
|
||||
indexOfFirstStatement = addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
|
||||
const indexAfterLastPrologueStatement = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
|
||||
const superStatementIndex = findSuperStatementIndex(body.statements, indexAfterLastPrologueStatement);
|
||||
|
||||
// Add parameters with property assignments. Transforms this:
|
||||
// If there was a super call, visit existing statements up to and including it
|
||||
if (superStatementIndex >= 0) {
|
||||
addRange(
|
||||
statements,
|
||||
visitNodes(body.statements, visitor, isStatement, indexAfterLastPrologueStatement, superStatementIndex + 1 - indexAfterLastPrologueStatement),
|
||||
);
|
||||
}
|
||||
|
||||
// Transform parameters into property assignments. Transforms this:
|
||||
//
|
||||
// constructor (public x, public y) {
|
||||
// }
|
||||
@@ -1950,10 +1959,19 @@ namespace ts {
|
||||
// this.y = y;
|
||||
// }
|
||||
//
|
||||
addRange(statements, map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
|
||||
const parameterPropertyAssignments = mapDefined(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment);
|
||||
|
||||
// Add the existing statements, skipping the initial super call.
|
||||
addRange(statements, visitNodes(body.statements, visitor, isStatement, indexOfFirstStatement));
|
||||
// If there is a super() call, the parameter properties go immediately after it
|
||||
if (superStatementIndex >= 0) {
|
||||
addRange(statements, parameterPropertyAssignments);
|
||||
}
|
||||
// Since there was no super() call, parameter properties are the first statements in the constructor
|
||||
else {
|
||||
statements = addRange(parameterPropertyAssignments, statements);
|
||||
}
|
||||
|
||||
// Add remaining statements from the body, skipping the super() call if it was found
|
||||
addRange(statements, visitNodes(body.statements, visitor, isStatement, superStatementIndex + 1));
|
||||
|
||||
// End the lexical environment.
|
||||
statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
|
||||
@@ -2237,11 +2255,10 @@ namespace ts {
|
||||
// we can safely elide the parentheses here, as a new synthetic
|
||||
// ParenthesizedExpression will be inserted if we remove parentheses too
|
||||
// aggressively.
|
||||
// HOWEVER - if there are leading comments on the expression itself, to handle ASI
|
||||
// correctly for return and throw, we must keep the parenthesis
|
||||
if (length(getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
|
||||
return factory.updateParenthesizedExpression(node, expression);
|
||||
}
|
||||
//
|
||||
// If there are leading comments on the expression itself, the emitter will handle ASI
|
||||
// for return, throw, and yield by re-introducing parenthesis during emit on an as-need
|
||||
// basis.
|
||||
return factory.createPartiallyEmittedExpression(expression, node);
|
||||
}
|
||||
|
||||
@@ -2507,6 +2524,7 @@ namespace ts {
|
||||
|| (isExternalModuleExport(node)
|
||||
&& moduleKind !== ModuleKind.ES2015
|
||||
&& moduleKind !== ModuleKind.ES2020
|
||||
&& moduleKind !== ModuleKind.ES2022
|
||||
&& moduleKind !== ModuleKind.ESNext
|
||||
&& moduleKind !== ModuleKind.System);
|
||||
}
|
||||
@@ -2816,7 +2834,8 @@ namespace ts {
|
||||
/*decorators*/ undefined,
|
||||
/*modifiers*/ undefined,
|
||||
importClause,
|
||||
node.moduleSpecifier)
|
||||
node.moduleSpecifier,
|
||||
node.assertClause)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -2844,9 +2863,12 @@ namespace ts {
|
||||
return shouldEmitAliasDeclaration(node) ? node : undefined;
|
||||
}
|
||||
else {
|
||||
// Elide named imports if all of its import specifiers are elided.
|
||||
// Elide named imports if all of its import specifiers are elided and settings allow.
|
||||
const allowEmpty = compilerOptions.preserveValueImports && (
|
||||
compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve ||
|
||||
compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error);
|
||||
const elements = visitNodes(node.elements, visitImportSpecifier, isImportSpecifier);
|
||||
return some(elements) ? factory.updateNamedImports(node, elements) : undefined;
|
||||
return allowEmpty || some(elements) ? factory.updateNamedImports(node, elements) : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2856,7 +2878,7 @@ namespace ts {
|
||||
* @param node The import specifier node.
|
||||
*/
|
||||
function visitImportSpecifier(node: ImportSpecifier): VisitResult<ImportSpecifier> {
|
||||
return shouldEmitAliasDeclaration(node) ? node : undefined;
|
||||
return !node.isTypeOnly && shouldEmitAliasDeclaration(node) ? node : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2889,13 +2911,15 @@ namespace ts {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (!resolver.isValueAliasDeclaration(node)) {
|
||||
// Elide the export declaration if it does not export a value.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Elide the export declaration if all of its named exports are elided.
|
||||
const exportClause = visitNode(node.exportClause, visitNamedExportBindings, isNamedExportBindings);
|
||||
const allowEmpty = !!node.moduleSpecifier && (
|
||||
compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Preserve ||
|
||||
compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error);
|
||||
const exportClause = visitNode(
|
||||
node.exportClause,
|
||||
(bindings: NamedExportBindings) => visitNamedExportBindings(bindings, allowEmpty),
|
||||
isNamedExportBindings);
|
||||
|
||||
return exportClause
|
||||
? factory.updateExportDeclaration(
|
||||
node,
|
||||
@@ -2903,7 +2927,8 @@ namespace ts {
|
||||
/*modifiers*/ undefined,
|
||||
node.isTypeOnly,
|
||||
exportClause,
|
||||
node.moduleSpecifier)
|
||||
node.moduleSpecifier,
|
||||
node.assertClause)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@@ -2913,18 +2938,18 @@ namespace ts {
|
||||
*
|
||||
* @param node The named exports node.
|
||||
*/
|
||||
function visitNamedExports(node: NamedExports): VisitResult<NamedExports> {
|
||||
function visitNamedExports(node: NamedExports, allowEmpty: boolean): VisitResult<NamedExports> {
|
||||
// Elide the named exports if all of its export specifiers were elided.
|
||||
const elements = visitNodes(node.elements, visitExportSpecifier, isExportSpecifier);
|
||||
return some(elements) ? factory.updateNamedExports(node, elements) : undefined;
|
||||
return allowEmpty || some(elements) ? factory.updateNamedExports(node, elements) : undefined;
|
||||
}
|
||||
|
||||
function visitNamespaceExports(node: NamespaceExport): VisitResult<NamespaceExport> {
|
||||
return factory.updateNamespaceExport(node, visitNode(node.name, visitor, isIdentifier));
|
||||
}
|
||||
|
||||
function visitNamedExportBindings(node: NamedExportBindings): VisitResult<NamedExportBindings> {
|
||||
return isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
|
||||
function visitNamedExportBindings(node: NamedExportBindings, allowEmpty: boolean): VisitResult<NamedExportBindings> {
|
||||
return isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node, allowEmpty);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2934,7 +2959,7 @@ namespace ts {
|
||||
*/
|
||||
function visitExportSpecifier(node: ExportSpecifier): VisitResult<ExportSpecifier> {
|
||||
// Elide an export specifier if it does not reference a value.
|
||||
return resolver.isValueAliasDeclaration(node) ? node : undefined;
|
||||
return !node.isTypeOnly && resolver.isValueAliasDeclaration(node) ? node : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2973,6 +2998,7 @@ namespace ts {
|
||||
/*modifiers*/ undefined,
|
||||
/*importClause*/ undefined,
|
||||
node.moduleReference.expression,
|
||||
/*assertClause*/ undefined
|
||||
),
|
||||
node,
|
||||
),
|
||||
|
||||
@@ -299,35 +299,32 @@ namespace ts {
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds super call and preceding prologue directives into the list of statements.
|
||||
*
|
||||
* @param ctor The constructor node.
|
||||
* @param result The list of statements.
|
||||
* @param visitor The visitor to apply to each node added to the result array.
|
||||
* @returns index of the statement that follows super call
|
||||
* @returns Contained super() call from descending into the statement ignoring parentheses, if that call exists.
|
||||
*/
|
||||
export function addPrologueDirectivesAndInitialSuperCall(factory: NodeFactory, ctor: ConstructorDeclaration, result: Statement[], visitor: Visitor): number {
|
||||
if (ctor.body) {
|
||||
const statements = ctor.body.statements;
|
||||
// add prologue directives to the list (if any)
|
||||
const index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor);
|
||||
if (index === statements.length) {
|
||||
// list contains nothing but prologue directives (or empty) - exit
|
||||
return index;
|
||||
}
|
||||
|
||||
const superIndex = findIndex(statements, s => isExpressionStatement(s) && isSuperCall(s.expression), index);
|
||||
if (superIndex > -1) {
|
||||
for (let i = index; i <= superIndex; i++) {
|
||||
result.push(visitNode(statements[i], visitor, isStatement));
|
||||
}
|
||||
return superIndex + 1;
|
||||
}
|
||||
|
||||
return index;
|
||||
export function getSuperCallFromStatement(statement: Statement) {
|
||||
if (!isExpressionStatement(statement)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return 0;
|
||||
const expression = skipParentheses(statement.expression);
|
||||
return isSuperCall(expression)
|
||||
? expression
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns The index (after prologue statements) of a super call, or -1 if not found.
|
||||
*/
|
||||
export function findSuperStatementIndex(statements: NodeArray<Statement>, indexAfterLastPrologueStatement: number) {
|
||||
for (let i = indexAfterLastPrologueStatement; i < statements.length; i += 1) {
|
||||
const statement = statements[i];
|
||||
|
||||
if (getSuperCallFromStatement(statement)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -76,7 +76,12 @@ namespace ts {
|
||||
return fileExtensionIs(fileName, Extension.Dts);
|
||||
}
|
||||
|
||||
export type ReportEmitErrorSummary = (errorCount: number) => void;
|
||||
export type ReportEmitErrorSummary = (errorCount: number, filesInError: (ReportFileInError | undefined)[]) => void;
|
||||
|
||||
export interface ReportFileInError {
|
||||
fileName: string;
|
||||
line: number;
|
||||
}
|
||||
|
||||
export interface SolutionBuilderHostBase<T extends BuilderProgram> extends ProgramHost<T> {
|
||||
createDirectory?(path: string): void;
|
||||
@@ -281,14 +286,15 @@ namespace ts {
|
||||
const moduleResolutionCache = !compilerHost.resolveModuleNames ? createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
|
||||
const typeReferenceDirectiveResolutionCache = !compilerHost.resolveTypeReferenceDirectives ? createTypeReferenceDirectiveResolutionCache(currentDirectory, getCanonicalFileName, /*options*/ undefined, moduleResolutionCache?.getPackageJsonInfoCache()) : undefined;
|
||||
if (!compilerHost.resolveModuleNames) {
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule!;
|
||||
compilerHost.resolveModuleNames = (moduleNames, containingFile, _reusedNames, redirectedReference) =>
|
||||
loadWithLocalCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader);
|
||||
const loader = (moduleName: string, resolverMode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference, resolverMode).resolvedModule!;
|
||||
compilerHost.resolveModuleNames = (moduleNames, containingFile, _reusedNames, redirectedReference, _options, containingSourceFile) =>
|
||||
loadWithModeAwareCache<ResolvedModuleFull>(Debug.checkEachDefined(moduleNames), Debug.checkDefined(containingSourceFile), containingFile, redirectedReference, loader);
|
||||
compilerHost.getModuleResolutionCache = () => moduleResolutionCache;
|
||||
}
|
||||
if (!compilerHost.resolveTypeReferenceDirectives) {
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined) => resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache).resolvedTypeReferenceDirective!;
|
||||
compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile, redirectedReference) =>
|
||||
loadWithLocalCache<ResolvedTypeReferenceDirective>(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader);
|
||||
const loader = (moduleName: string, containingFile: string, redirectedReference: ResolvedProjectReference | undefined, containingFileMode: SourceFile["impliedNodeFormat"] | undefined) => resolveTypeReferenceDirective(moduleName, containingFile, state.projectCompilerOptions, compilerHost, redirectedReference, state.typeReferenceDirectiveResolutionCache, containingFileMode).resolvedTypeReferenceDirective!;
|
||||
compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) =>
|
||||
loadWithTypeDirectiveCache<ResolvedTypeReferenceDirective>(Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, containingFileMode, loader);
|
||||
}
|
||||
|
||||
const { watchFile, watchDirectory, writeLog } = createWatchFactory<ResolvedConfigFileName>(hostWithWatch, options);
|
||||
@@ -871,12 +877,12 @@ namespace ts {
|
||||
getConfigFileParsingDiagnostics(config),
|
||||
config.projectReferences
|
||||
);
|
||||
state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && map(
|
||||
state.moduleResolutionCache.getPackageJsonInfoCache().entries(),
|
||||
([path, data]) => ([state.host.realpath ? toPath(state, state.host.realpath(path)) : path, data] as const)
|
||||
));
|
||||
|
||||
if (state.watch) {
|
||||
state.lastCachedPackageJsonLookups.set(projectPath, state.moduleResolutionCache && map(
|
||||
state.moduleResolutionCache.getPackageJsonInfoCache().entries(),
|
||||
([path, data]) => ([state.host.realpath && data ? toPath(state, state.host.realpath(path)) : path, data] as const)
|
||||
));
|
||||
|
||||
state.builderPrograms.set(projectPath, program);
|
||||
}
|
||||
step++;
|
||||
@@ -2002,10 +2008,12 @@ namespace ts {
|
||||
const canReportSummary = state.watch || !!state.host.reportErrorSummary;
|
||||
const { diagnostics } = state;
|
||||
let totalErrors = 0;
|
||||
let filesInError: (ReportFileInError | undefined)[] = [];
|
||||
if (isCircularBuildOrder(buildOrder)) {
|
||||
reportBuildQueue(state, buildOrder.buildOrder);
|
||||
reportErrors(state, buildOrder.circularDiagnostics);
|
||||
if (canReportSummary) totalErrors += getErrorCountForSummary(buildOrder.circularDiagnostics);
|
||||
if (canReportSummary) filesInError = [...filesInError, ...getFilesInErrorForSummary(buildOrder.circularDiagnostics)];
|
||||
}
|
||||
else {
|
||||
// Report errors from the other projects
|
||||
@@ -2016,13 +2024,14 @@ namespace ts {
|
||||
}
|
||||
});
|
||||
if (canReportSummary) diagnostics.forEach(singleProjectErrors => totalErrors += getErrorCountForSummary(singleProjectErrors));
|
||||
if (canReportSummary) diagnostics.forEach(singleProjectErrors => [...filesInError, ...getFilesInErrorForSummary(singleProjectErrors)]);
|
||||
}
|
||||
|
||||
if (state.watch) {
|
||||
reportWatchStatus(state, getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
|
||||
}
|
||||
else if (state.host.reportErrorSummary) {
|
||||
state.host.reportErrorSummary(totalErrors);
|
||||
state.host.reportErrorSummary(totalErrors, filesInError);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@
|
||||
"transformers/module/module.ts",
|
||||
"transformers/module/system.ts",
|
||||
"transformers/module/esnextAnd2015.ts",
|
||||
"transformers/module/node.ts",
|
||||
"transformers/declarations/diagnostics.ts",
|
||||
"transformers/declarations.ts",
|
||||
"transformer.ts",
|
||||
|
||||
+229
-71
@@ -161,6 +161,7 @@ namespace ts {
|
||||
AbstractKeyword,
|
||||
AsKeyword,
|
||||
AssertsKeyword,
|
||||
AssertKeyword,
|
||||
AnyKeyword,
|
||||
AsyncKeyword,
|
||||
AwaitKeyword,
|
||||
@@ -341,6 +342,8 @@ namespace ts {
|
||||
DefaultClause,
|
||||
HeritageClause,
|
||||
CatchClause,
|
||||
AssertClause,
|
||||
AssertEntry,
|
||||
|
||||
// Property assignments
|
||||
PropertyAssignment,
|
||||
@@ -544,6 +547,7 @@ namespace ts {
|
||||
| SyntaxKind.AnyKeyword
|
||||
| SyntaxKind.AsKeyword
|
||||
| SyntaxKind.AssertsKeyword
|
||||
| SyntaxKind.AssertKeyword
|
||||
| SyntaxKind.AsyncKeyword
|
||||
| SyntaxKind.AwaitKeyword
|
||||
| SyntaxKind.BigIntKeyword
|
||||
@@ -925,6 +929,8 @@ namespace ts {
|
||||
| JSDocFunctionType
|
||||
| ExportDeclaration
|
||||
| NamedTupleMember
|
||||
| ExportSpecifier
|
||||
| CaseClause
|
||||
| EndOfFileToken
|
||||
;
|
||||
|
||||
@@ -1039,6 +1045,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export type AssertsKeyword = KeywordToken<SyntaxKind.AssertsKeyword>;
|
||||
export type AssertKeyword = KeywordToken<SyntaxKind.AssertKeyword>;
|
||||
export type AwaitKeyword = KeywordToken<SyntaxKind.AwaitKeyword>;
|
||||
|
||||
/** @deprecated Use `AwaitKeyword` instead. */
|
||||
@@ -1209,7 +1216,8 @@ namespace ts {
|
||||
readonly expression: Expression;
|
||||
}
|
||||
|
||||
export interface PrivateIdentifier extends Node {
|
||||
// Typed as a PrimaryExpression due to its presence in BinaryExpressions (#field in expr)
|
||||
export interface PrivateIdentifier extends PrimaryExpression {
|
||||
readonly kind: SyntaxKind.PrivateIdentifier;
|
||||
// escaping not strictly necessary
|
||||
// avoids gotchas in transforms and utils
|
||||
@@ -1603,12 +1611,12 @@ namespace ts {
|
||||
export interface TypePredicateNode extends TypeNode {
|
||||
readonly kind: SyntaxKind.TypePredicate;
|
||||
readonly parent: SignatureDeclaration | JSDocTypeExpression;
|
||||
readonly assertsModifier?: AssertsToken;
|
||||
readonly assertsModifier?: AssertsKeyword;
|
||||
readonly parameterName: Identifier | ThisTypeNode;
|
||||
readonly type?: TypeNode;
|
||||
}
|
||||
|
||||
export interface TypeQueryNode extends TypeNode {
|
||||
export interface TypeQueryNode extends NodeWithTypeArguments {
|
||||
readonly kind: SyntaxKind.TypeQuery;
|
||||
readonly exprName: EntityName;
|
||||
}
|
||||
@@ -1696,11 +1704,13 @@ namespace ts {
|
||||
|
||||
export interface MappedTypeNode extends TypeNode, Declaration {
|
||||
readonly kind: SyntaxKind.MappedType;
|
||||
readonly readonlyToken?: ReadonlyToken | PlusToken | MinusToken;
|
||||
readonly readonlyToken?: ReadonlyKeyword | PlusToken | MinusToken;
|
||||
readonly typeParameter: TypeParameterDeclaration;
|
||||
readonly nameType?: TypeNode;
|
||||
readonly questionToken?: QuestionToken | PlusToken | MinusToken;
|
||||
readonly type?: TypeNode;
|
||||
/** Used only to produce grammar errors */
|
||||
readonly members?: NodeArray<TypeElement>;
|
||||
}
|
||||
|
||||
export interface LiteralTypeNode extends TypeNode {
|
||||
@@ -2436,9 +2446,8 @@ namespace ts {
|
||||
readonly expression: ImportExpression;
|
||||
}
|
||||
|
||||
export interface ExpressionWithTypeArguments extends NodeWithTypeArguments {
|
||||
export interface ExpressionWithTypeArguments extends MemberExpression, NodeWithTypeArguments {
|
||||
readonly kind: SyntaxKind.ExpressionWithTypeArguments;
|
||||
readonly parent: HeritageClause | JSDocAugmentsTag | JSDocImplementsTag;
|
||||
readonly expression: LeftHandSideExpression;
|
||||
}
|
||||
|
||||
@@ -2748,7 +2757,7 @@ namespace ts {
|
||||
|
||||
export interface ForOfStatement extends IterationStatement {
|
||||
readonly kind: SyntaxKind.ForOfStatement;
|
||||
readonly awaitModifier?: AwaitKeywordToken;
|
||||
readonly awaitModifier?: AwaitKeyword;
|
||||
readonly initializer: ForInitializer;
|
||||
readonly expression: Expression;
|
||||
}
|
||||
@@ -2792,7 +2801,7 @@ namespace ts {
|
||||
readonly clauses: NodeArray<CaseOrDefaultClause>;
|
||||
}
|
||||
|
||||
export interface CaseClause extends Node {
|
||||
export interface CaseClause extends Node, JSDocContainer {
|
||||
readonly kind: SyntaxKind.CaseClause;
|
||||
readonly parent: CaseBlock;
|
||||
readonly expression: Expression;
|
||||
@@ -3014,6 +3023,7 @@ namespace ts {
|
||||
readonly importClause?: ImportClause;
|
||||
/** If this is not a StringLiteral it will be a grammar error. */
|
||||
readonly moduleSpecifier: Expression;
|
||||
readonly assertClause?: AssertClause;
|
||||
}
|
||||
|
||||
export type NamedImportBindings =
|
||||
@@ -3040,6 +3050,22 @@ namespace ts {
|
||||
readonly namedBindings?: NamedImportBindings;
|
||||
}
|
||||
|
||||
export type AssertionKey = Identifier | StringLiteral;
|
||||
|
||||
export interface AssertEntry extends Node {
|
||||
readonly kind: SyntaxKind.AssertEntry;
|
||||
readonly parent: AssertClause;
|
||||
readonly name: AssertionKey;
|
||||
readonly value: Expression;
|
||||
}
|
||||
|
||||
export interface AssertClause extends Node {
|
||||
readonly kind: SyntaxKind.AssertClause;
|
||||
readonly parent: ImportDeclaration | ExportDeclaration
|
||||
readonly elements: NodeArray<AssertEntry>;
|
||||
readonly multiLine?: boolean;
|
||||
}
|
||||
|
||||
export interface NamespaceImport extends NamedDeclaration {
|
||||
readonly kind: SyntaxKind.NamespaceImport;
|
||||
readonly parent: ImportClause;
|
||||
@@ -3067,6 +3093,7 @@ namespace ts {
|
||||
readonly exportClause?: NamedExportBindings;
|
||||
/** If this is not a StringLiteral it will be a grammar error. */
|
||||
readonly moduleSpecifier?: Expression;
|
||||
readonly assertClause?: AssertClause;
|
||||
}
|
||||
|
||||
export interface NamedImports extends Node {
|
||||
@@ -3088,11 +3115,13 @@ namespace ts {
|
||||
readonly parent: NamedImports;
|
||||
readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
|
||||
readonly name: Identifier; // Declared name
|
||||
readonly isTypeOnly: boolean;
|
||||
}
|
||||
|
||||
export interface ExportSpecifier extends NamedDeclaration {
|
||||
export interface ExportSpecifier extends NamedDeclaration, JSDocContainer {
|
||||
readonly kind: SyntaxKind.ExportSpecifier;
|
||||
readonly parent: NamedExports;
|
||||
readonly isTypeOnly: boolean;
|
||||
readonly propertyName?: Identifier; // Name preceding "as" keyword (or undefined when "as" is absent)
|
||||
readonly name: Identifier; // Declared name
|
||||
}
|
||||
@@ -3113,8 +3142,8 @@ namespace ts {
|
||||
| ImportClause & { readonly isTypeOnly: true, readonly name: Identifier }
|
||||
| ImportEqualsDeclaration & { readonly isTypeOnly: true }
|
||||
| NamespaceImport & { readonly parent: ImportClause & { readonly isTypeOnly: true } }
|
||||
| ImportSpecifier & { readonly parent: NamedImports & { readonly parent: ImportClause & { readonly isTypeOnly: true } } }
|
||||
| ExportSpecifier & { readonly parent: NamedExports & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true } } }
|
||||
| ImportSpecifier & ({ readonly isTypeOnly: true } | { readonly parent: NamedImports & { readonly parent: ImportClause & { readonly isTypeOnly: true } } })
|
||||
| ExportSpecifier & ({ readonly isTypeOnly: true } | { readonly parent: NamedExports & { readonly parent: ExportDeclaration & { readonly isTypeOnly: true } } })
|
||||
;
|
||||
|
||||
/**
|
||||
@@ -3130,6 +3159,7 @@ namespace ts {
|
||||
|
||||
export interface FileReference extends TextRange {
|
||||
fileName: string;
|
||||
resolutionMode?: SourceFile["impliedNodeFormat"];
|
||||
}
|
||||
|
||||
export interface CheckJsDirective extends TextRange {
|
||||
@@ -3560,6 +3590,20 @@ namespace ts {
|
||||
hasNoDefaultLib: boolean;
|
||||
|
||||
languageVersion: ScriptTarget;
|
||||
|
||||
/**
|
||||
* When `module` is `Node12` or `NodeNext`, this field controls whether the
|
||||
* source file in question is an ESNext-output-format file, or a CommonJS-output-format
|
||||
* module. This is derived by the module resolver as it looks up the file, since
|
||||
* it is derived from either the file extension of the module, or the containing
|
||||
* `package.json` context, and affects both checking and emit.
|
||||
*
|
||||
* It is _public_ so that (pre)transformers can set this field,
|
||||
* since it switches the builtin `node` module transform. Generally speaking, if unset,
|
||||
* the field is treated as though it is `ModuleKind.CommonJS`.
|
||||
*/
|
||||
impliedNodeFormat?: ModuleKind.ESNext | ModuleKind.CommonJS;
|
||||
|
||||
/* @internal */ scriptKind: ScriptKind;
|
||||
|
||||
/**
|
||||
@@ -3601,8 +3645,8 @@ namespace ts {
|
||||
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
|
||||
// It is used to resolve module names in the checker.
|
||||
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
|
||||
/* @internal */ resolvedModules?: ESMap<string, ResolvedModuleFull | undefined>;
|
||||
/* @internal */ resolvedTypeReferenceDirectiveNames: ESMap<string, ResolvedTypeReferenceDirective | undefined>;
|
||||
/* @internal */ resolvedModules?: ModeAwareCache<ResolvedModuleFull | undefined>;
|
||||
/* @internal */ resolvedTypeReferenceDirectiveNames: ModeAwareCache<ResolvedTypeReferenceDirective | undefined>;
|
||||
/* @internal */ imports: readonly StringLiteralLike[];
|
||||
// Identifier only if `declare global`
|
||||
/* @internal */ moduleAugmentations: readonly (StringLiteral | Identifier)[];
|
||||
@@ -3669,7 +3713,7 @@ namespace ts {
|
||||
|
||||
// References and noDefaultLibAre Dts only
|
||||
referencedFiles: readonly FileReference[];
|
||||
typeReferenceDirectives: readonly string[] | undefined;
|
||||
typeReferenceDirectives: readonly FileReference[] | undefined;
|
||||
libReferenceDirectives: readonly FileReference[];
|
||||
hasNoDefaultLib?: boolean;
|
||||
|
||||
@@ -3962,7 +4006,7 @@ namespace ts {
|
||||
getRelationCacheSizes(): { assignable: number, identity: number, subtype: number, strictSubtype: number };
|
||||
|
||||
/* @internal */ getFileProcessingDiagnostics(): FilePreprocessingDiagnostics[] | undefined;
|
||||
/* @internal */ getResolvedTypeReferenceDirectives(): ESMap<string, ResolvedTypeReferenceDirective | undefined>;
|
||||
/* @internal */ getResolvedTypeReferenceDirectives(): ModeAwareCache<ResolvedTypeReferenceDirective | undefined>;
|
||||
isSourceFileFromExternalLibrary(file: SourceFile): boolean;
|
||||
isSourceFileDefaultLibrary(file: SourceFile): boolean;
|
||||
|
||||
@@ -3984,7 +4028,7 @@ namespace ts {
|
||||
/* @internal */ getFileIncludeReasons(): MultiMap<Path, FileIncludeReason>;
|
||||
/* @internal */ useCaseSensitiveFileNames(): boolean;
|
||||
|
||||
/* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string): ResolvedModuleWithFailedLookupLocations | undefined;
|
||||
/* @internal */ getResolvedModuleWithFailedLookupLocationsFromCache(moduleName: string, containingFile: string, mode?: ModuleKind.CommonJS | ModuleKind.ESNext): ResolvedModuleWithFailedLookupLocations | undefined;
|
||||
|
||||
getProjectReferences(): readonly ProjectReference[] | undefined;
|
||||
getResolvedProjectReferences(): readonly (ResolvedProjectReference | undefined)[] | undefined;
|
||||
@@ -4102,7 +4146,7 @@ namespace ts {
|
||||
|
||||
getSourceFiles(): readonly SourceFile[];
|
||||
getSourceFile(fileName: string): SourceFile | undefined;
|
||||
getResolvedTypeReferenceDirectives(): ReadonlyESMap<string, ResolvedTypeReferenceDirective | undefined>;
|
||||
getResolvedTypeReferenceDirectives(): ModeAwareCache<ResolvedTypeReferenceDirective | undefined>;
|
||||
getProjectReferenceRedirect(fileName: string): string | undefined;
|
||||
isSourceOfProjectReferenceRedirect(fileName: string): boolean;
|
||||
|
||||
@@ -4111,6 +4155,7 @@ namespace ts {
|
||||
|
||||
export interface TypeChecker {
|
||||
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
|
||||
/* @internal */ getTypeOfSymbol(symbol: Symbol): Type;
|
||||
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
|
||||
getPropertiesOfType(type: Type): Symbol[];
|
||||
getPropertyOfType(type: Type, propertyName: string): Symbol | undefined;
|
||||
@@ -4120,6 +4165,7 @@ namespace ts {
|
||||
getIndexInfosOfType(type: Type): readonly IndexInfo[];
|
||||
getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[];
|
||||
getIndexTypeOfType(type: Type, kind: IndexKind): Type | undefined;
|
||||
/* @internal */ getIndexType(type: Type): Type;
|
||||
getBaseTypes(type: InterfaceType): BaseType[];
|
||||
getBaseTypeOfLiteralType(type: Type): Type;
|
||||
getWidenedType(type: Type): Type;
|
||||
@@ -4371,6 +4417,15 @@ namespace ts {
|
||||
/* @internal */ getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol: Symbol): readonly TypeParameter[] | undefined;
|
||||
/* @internal */ isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean;
|
||||
/* @internal */ isPropertyAccessible(node: Node, isSuper: boolean, isWrite: boolean, containingType: Type, property: Symbol): boolean;
|
||||
/* @internal */ getTypeOnlyAliasDeclaration(symbol: Symbol): TypeOnlyAliasDeclaration | undefined;
|
||||
/* @internal */ getMemberOverrideModifierStatus(node: ClassLikeDeclaration, member: ClassElement): MemberOverrideStatus;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const enum MemberOverrideStatus {
|
||||
Ok,
|
||||
NeedsOverride,
|
||||
HasInvalidOverride
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -4586,7 +4641,7 @@ namespace ts {
|
||||
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
|
||||
|
||||
/* @internal */
|
||||
export type AnyImportOrRequire = AnyImportSyntax | RequireVariableDeclaration;
|
||||
export type AnyImportOrRequire = AnyImportSyntax | VariableDeclarationInitializedTo<RequireOrImportCall>;
|
||||
|
||||
/* @internal */
|
||||
export type AnyImportOrRequireStatement = AnyImportSyntax | RequireVariableStatement;
|
||||
@@ -4611,8 +4666,8 @@ namespace ts {
|
||||
export type RequireOrImportCall = CallExpression & { expression: Identifier, arguments: [StringLiteralLike] };
|
||||
|
||||
/* @internal */
|
||||
export interface RequireVariableDeclaration extends VariableDeclaration {
|
||||
readonly initializer: RequireOrImportCall;
|
||||
export interface VariableDeclarationInitializedTo<T extends Expression> extends VariableDeclaration {
|
||||
readonly initializer: T;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -4622,7 +4677,7 @@ namespace ts {
|
||||
|
||||
/* @internal */
|
||||
export interface RequireVariableDeclarationList extends VariableDeclarationList {
|
||||
readonly declarations: NodeArray<RequireVariableDeclaration>;
|
||||
readonly declarations: NodeArray<VariableDeclarationInitializedTo<RequireOrImportCall>>;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -4734,8 +4789,8 @@ namespace ts {
|
||||
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
|
||||
isArgumentsLocalBinding(node: Identifier): boolean;
|
||||
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration | ImportTypeNode | ImportCall): SourceFile | undefined;
|
||||
getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[] | undefined;
|
||||
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[] | undefined;
|
||||
getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined;
|
||||
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): [specifier: string, mode: SourceFile["impliedNodeFormat"] | undefined][] | undefined;
|
||||
isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean;
|
||||
getJsxFactoryEntity(location?: Node): EntityName | undefined;
|
||||
getJsxFragmentFactoryEntity(location?: Node): EntityName | undefined;
|
||||
@@ -4898,9 +4953,10 @@ namespace ts {
|
||||
extendedContainersByFile?: ESMap<NodeId, Symbol[]>; // Containers (other than the parent) which this symbol is aliased in
|
||||
variances?: VarianceFlags[]; // Alias symbol type argument variance cache
|
||||
deferralConstituents?: Type[]; // Calculated list of constituents for a deferred type
|
||||
deferralWriteConstituents?: Type[]; // Constituents of a deferred `writeType`
|
||||
deferralParent?: Type; // Source union/intersection of a deferred type
|
||||
cjsExportMerged?: Symbol; // Version of the symbol with all non export= exports merged with the export= target
|
||||
typeOnlyDeclaration?: TypeOnlyCompatibleAliasDeclaration | false; // First resolved alias declaration that makes the symbol only usable in type constructs
|
||||
typeOnlyDeclaration?: TypeOnlyAliasDeclaration | false; // First resolved alias declaration that makes the symbol only usable in type constructs
|
||||
isConstructorDeclaredProperty?: boolean; // Property declared through 'this.x = ...' assignment in constructor
|
||||
tupleLabelDeclaration?: NamedTupleMember | ParameterDeclaration; // Declaration associated with the tuple's label
|
||||
accessibleChainCache?: ESMap<string, Symbol[] | undefined>;
|
||||
@@ -4934,6 +4990,7 @@ namespace ts {
|
||||
HasNeverType = 1 << 17, // Synthetic property with at least one never type in constituents
|
||||
Mapped = 1 << 18, // Property of mapped type
|
||||
StripOptional = 1 << 19, // Strip optionality in mapped property
|
||||
Unresolved = 1 << 20, // Unresolved type alias symbol
|
||||
Synthetic = SyntheticProperty | SyntheticMethod,
|
||||
Discriminant = HasNonUniformType | HasLiteralType,
|
||||
Partial = ReadPartial | WritePartial
|
||||
@@ -5031,6 +5088,7 @@ namespace ts {
|
||||
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.
|
||||
ContainsSuperPropertyInStaticInitializer = 0x08000000, // Marked on all block-scoped containers containing a static initializer with 'super.x' or 'super[x]'.
|
||||
InCheckIdentifier = 0x10000000,
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -5054,7 +5112,7 @@ namespace ts {
|
||||
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
|
||||
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
|
||||
outerTypeParameters?: TypeParameter[]; // Outer type parameters of anonymous object type
|
||||
isExhaustive?: boolean; // Is node an exhaustive switch statement
|
||||
@@ -5118,6 +5176,8 @@ namespace ts {
|
||||
ESSymbolLike = ESSymbol | UniqueESSymbol,
|
||||
VoidLike = Void | Undefined,
|
||||
/* @internal */
|
||||
DefinitelyNonNullable = StringLike | NumberLike | BigIntLike | BooleanLike | EnumLike | ESSymbolLike | Object | NonPrimitive,
|
||||
/* @internal */
|
||||
DisjointDomains = NonPrimitive | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbolLike | VoidLike | Null,
|
||||
UnionOrIntersection = Union | Intersection,
|
||||
StructuredType = Object | Union | Intersection,
|
||||
@@ -5135,20 +5195,22 @@ namespace ts {
|
||||
// 'Narrowable' types are types where narrowing actually narrows.
|
||||
// This *should* be every type other than null, undefined, void, and never
|
||||
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
|
||||
/* @internal */
|
||||
IncludesMask = Any | Unknown | Primitive | Never | Object | Union | Intersection | NonPrimitive | TemplateLiteral,
|
||||
// The following flags are used for different purposes during union and intersection type construction
|
||||
/* @internal */
|
||||
IncludesStructuredOrInstantiable = TypeParameter,
|
||||
IncludesMissingType = TypeParameter,
|
||||
/* @internal */
|
||||
IncludesNonWideningType = Index,
|
||||
/* @internal */
|
||||
IncludesWildcard = IndexedAccess,
|
||||
/* @internal */
|
||||
IncludesEmptyObject = Conditional,
|
||||
/* @internal */
|
||||
IncludesInstantiable = Substitution,
|
||||
/* @internal */
|
||||
NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | Object | Intersection | IncludesInstantiable,
|
||||
}
|
||||
|
||||
export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
|
||||
@@ -5272,13 +5334,14 @@ namespace ts {
|
||||
// Flags that require TypeFlags.Object
|
||||
ContainsSpread = 1 << 22, // Object literal contains spread operation
|
||||
ObjectRestType = 1 << 23, // Originates in object rest declaration
|
||||
InstantiationExpressionType = 1 << 24, // Originates in instantiation expression
|
||||
/* @internal */
|
||||
IsClassInstanceClone = 1 << 24, // Type is a clone of a class instance type
|
||||
IsClassInstanceClone = 1 << 25, // Type is a clone of a class instance type
|
||||
// Flags that require TypeFlags.Object and ObjectFlags.Reference
|
||||
/* @internal */
|
||||
IdenticalBaseTypeCalculated = 1 << 25, // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already
|
||||
IdenticalBaseTypeCalculated = 1 << 26, // has had `getSingleBaseForNonAugmentingSubtype` invoked on it already
|
||||
/* @internal */
|
||||
IdenticalBaseTypeExists = 1 << 26, // has a defined cachedEquivalentBaseType member
|
||||
IdenticalBaseTypeExists = 1 << 27, // has a defined cachedEquivalentBaseType member
|
||||
|
||||
// Flags that require TypeFlags.UnionOrIntersection or TypeFlags.Substitution
|
||||
/* @internal */
|
||||
@@ -5463,6 +5526,11 @@ namespace ts {
|
||||
instantiations?: ESMap<string, Type>; // Instantiations of generic type alias (undefined if non-generic)
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface InstantiationExpressionType extends AnonymousType {
|
||||
node: ExpressionWithTypeArguments | TypeQueryNode;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface MappedType extends AnonymousType {
|
||||
declaration: MappedTypeNode;
|
||||
@@ -5534,6 +5602,7 @@ namespace ts {
|
||||
/* @internal */
|
||||
export interface SyntheticDefaultModuleType extends Type {
|
||||
syntheticType?: Type;
|
||||
defaultOnlyType?: Type;
|
||||
}
|
||||
|
||||
export interface InstantiableType extends Type {
|
||||
@@ -5615,8 +5684,8 @@ namespace ts {
|
||||
root: ConditionalRoot;
|
||||
checkType: Type;
|
||||
extendsType: Type;
|
||||
resolvedTrueType: Type;
|
||||
resolvedFalseType: Type;
|
||||
resolvedTrueType?: Type;
|
||||
resolvedFalseType?: Type;
|
||||
/* @internal */
|
||||
resolvedInferredTrueType?: Type; // The `trueType` instantiated with the `combinedMapper`, if present
|
||||
/* @internal */
|
||||
@@ -5937,7 +6006,13 @@ namespace ts {
|
||||
|
||||
export enum ModuleResolutionKind {
|
||||
Classic = 1,
|
||||
NodeJs = 2
|
||||
NodeJs = 2,
|
||||
// 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
|
||||
// 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
|
||||
Node12 = 3,
|
||||
NodeNext = 99, // Not simply `Node12` so that compiled code linked against TS can use the `Next` value reliably (same as with `ModuleKind`)
|
||||
}
|
||||
|
||||
export interface PluginImport {
|
||||
@@ -6091,7 +6166,7 @@ namespace ts {
|
||||
suppressExcessPropertyErrors?: boolean;
|
||||
suppressImplicitAnyIndexErrors?: boolean;
|
||||
/* @internal */ suppressOutputPathCheck?: boolean;
|
||||
target?: ScriptTarget; // TODO: GH#18217 frequently asserted as defined
|
||||
target?: ScriptTarget;
|
||||
traceResolution?: boolean;
|
||||
useUnknownInCatchVariables?: boolean;
|
||||
resolveJsonModule?: boolean;
|
||||
@@ -6143,7 +6218,12 @@ namespace ts {
|
||||
// module kind).
|
||||
ES2015 = 5,
|
||||
ES2020 = 6,
|
||||
ESNext = 99
|
||||
ES2022 = 7,
|
||||
ESNext = 99,
|
||||
|
||||
// Node12+ is an amalgam of commonjs (albeit updated) and es2020+, and represents a distinct module system from es2020/esnext
|
||||
Node12 = 100,
|
||||
NodeNext = 199,
|
||||
}
|
||||
|
||||
export const enum JsxEmit {
|
||||
@@ -6200,6 +6280,7 @@ namespace ts {
|
||||
ES2019 = 6,
|
||||
ES2020 = 7,
|
||||
ES2021 = 8,
|
||||
ES2022 = 9,
|
||||
ESNext = 99,
|
||||
JSON = 100,
|
||||
Latest = ESNext,
|
||||
@@ -6266,7 +6347,7 @@ namespace ts {
|
||||
isFilePath?: boolean; // True if option value is a path or fileName
|
||||
shortName?: string; // A short mnemonic for convenience - for instance, 'h' can be used in place of 'help'
|
||||
description?: DiagnosticMessage; // The message describing what the command line switch does.
|
||||
defaultValueDescription?: string | DiagnosticMessage; // The message describing what the dafault value is. string type is prepared for fixed chosen like "false" which do not need I18n.
|
||||
defaultValueDescription?: string | number | boolean | DiagnosticMessage; // The message describing what the dafault value is. string type is prepared for fixed chosen like "false" which do not need I18n.
|
||||
paramType?: DiagnosticMessage; // The name to be used for a non-boolean option's parameter
|
||||
isTSConfigOnly?: boolean; // True if option can only be specified via tsconfig.json file
|
||||
isCommandLineOnly?: boolean;
|
||||
@@ -6284,13 +6365,27 @@ namespace ts {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface CommandLineOptionOfPrimitiveType extends CommandLineOptionBase {
|
||||
type: "string" | "number" | "boolean";
|
||||
export interface CommandLineOptionOfStringType extends CommandLineOptionBase {
|
||||
type: "string";
|
||||
defaultValueDescription?: string | undefined | DiagnosticMessage;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface CommandLineOptionOfNumberType extends CommandLineOptionBase {
|
||||
type: "number";
|
||||
defaultValueDescription: number | undefined | DiagnosticMessage;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface CommandLineOptionOfBooleanType extends CommandLineOptionBase {
|
||||
type: "boolean";
|
||||
defaultValueDescription: boolean | undefined | DiagnosticMessage;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface CommandLineOptionOfCustomType extends CommandLineOptionBase {
|
||||
type: ESMap<string, number | string>; // an object literal mapping named values to actual values
|
||||
defaultValueDescription: number | string | undefined | DiagnosticMessage;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -6317,11 +6412,11 @@ namespace ts {
|
||||
/* @internal */
|
||||
export interface CommandLineOptionOfListType extends CommandLineOptionBase {
|
||||
type: "list";
|
||||
element: CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption;
|
||||
element: CommandLineOptionOfCustomType | CommandLineOptionOfStringType | CommandLineOptionOfNumberType | CommandLineOptionOfBooleanType | TsConfigOnlyOption;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfPrimitiveType | TsConfigOnlyOption | CommandLineOptionOfListType;
|
||||
export type CommandLineOption = CommandLineOptionOfCustomType | CommandLineOptionOfStringType | CommandLineOptionOfNumberType | CommandLineOptionOfBooleanType | TsConfigOnlyOption | CommandLineOptionOfListType;
|
||||
|
||||
/* @internal */
|
||||
export const enum CharacterCodes {
|
||||
@@ -6539,7 +6634,13 @@ namespace ts {
|
||||
Js = ".js",
|
||||
Jsx = ".jsx",
|
||||
Json = ".json",
|
||||
TsBuildInfo = ".tsbuildinfo"
|
||||
TsBuildInfo = ".tsbuildinfo",
|
||||
Mjs = ".mjs",
|
||||
Mts = ".mts",
|
||||
Dmts = ".d.mts",
|
||||
Cjs = ".cjs",
|
||||
Cts = ".cts",
|
||||
Dcts = ".d.cts",
|
||||
}
|
||||
|
||||
export interface ResolvedModuleWithFailedLookupLocations {
|
||||
@@ -6594,11 +6695,15 @@ namespace ts {
|
||||
* If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
|
||||
* 'throw new Error("NotImplemented")'
|
||||
*/
|
||||
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedModule | undefined)[];
|
||||
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[];
|
||||
/**
|
||||
* Returns the module resolution cache used by a provided `resolveModuleNames` implementation so that any non-name module resolution operations (eg, package.json lookup) can reuse it
|
||||
*/
|
||||
getModuleResolutionCache?(): ModuleResolutionCache | undefined;
|
||||
/**
|
||||
* This method is a companion for 'resolveModuleNames' and is used to resolve 'types' references to actual type declaration files
|
||||
*/
|
||||
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
getEnvironmentVariable?(name: string): string | undefined;
|
||||
/* @internal */ onReleaseOldSourceFile?(oldSourceFile: SourceFile, oldOptions: CompilerOptions, hasSourceFileByPath: boolean): void;
|
||||
/* @internal */ onReleaseParsedCommandLine?(configFileName: string, oldResolvedRef: ResolvedProjectReference | undefined, optionOptions: CompilerOptions): void;
|
||||
@@ -6635,15 +6740,16 @@ namespace ts {
|
||||
ContainsTypeScript = 1 << 0,
|
||||
ContainsJsx = 1 << 1,
|
||||
ContainsESNext = 1 << 2,
|
||||
ContainsES2021 = 1 << 3,
|
||||
ContainsES2020 = 1 << 4,
|
||||
ContainsES2019 = 1 << 5,
|
||||
ContainsES2018 = 1 << 6,
|
||||
ContainsES2017 = 1 << 7,
|
||||
ContainsES2016 = 1 << 8,
|
||||
ContainsES2015 = 1 << 9,
|
||||
ContainsGenerator = 1 << 10,
|
||||
ContainsDestructuringAssignment = 1 << 11,
|
||||
ContainsES2022 = 1 << 3,
|
||||
ContainsES2021 = 1 << 4,
|
||||
ContainsES2020 = 1 << 5,
|
||||
ContainsES2019 = 1 << 6,
|
||||
ContainsES2018 = 1 << 7,
|
||||
ContainsES2017 = 1 << 8,
|
||||
ContainsES2016 = 1 << 9,
|
||||
ContainsES2015 = 1 << 10,
|
||||
ContainsGenerator = 1 << 11,
|
||||
ContainsDestructuringAssignment = 1 << 12,
|
||||
|
||||
// Markers
|
||||
// - Flags used to indicate that a subtree contains a specific transformation.
|
||||
@@ -6672,6 +6778,7 @@ namespace ts {
|
||||
AssertTypeScript = ContainsTypeScript,
|
||||
AssertJsx = ContainsJsx,
|
||||
AssertESNext = ContainsESNext,
|
||||
AssertES2022 = ContainsES2022,
|
||||
AssertES2021 = ContainsES2021,
|
||||
AssertES2020 = ContainsES2020,
|
||||
AssertES2019 = ContainsES2019,
|
||||
@@ -6737,6 +6844,31 @@ namespace ts {
|
||||
externalHelpers?: boolean;
|
||||
helpers?: EmitHelper[]; // Emit helpers for the node
|
||||
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 {
|
||||
@@ -6829,7 +6961,8 @@ namespace ts {
|
||||
MakeTemplateObject = 1 << 18, // __makeTemplateObject (used for constructing template string array objects)
|
||||
ClassPrivateFieldGet = 1 << 19, // __classPrivateFieldGet (used by the class private field transformation)
|
||||
ClassPrivateFieldSet = 1 << 20, // __classPrivateFieldSet (used by the class private field transformation)
|
||||
CreateBinding = 1 << 21, // __createBinding (use by the module transform for (re)exports and namespace imports)
|
||||
ClassPrivateFieldIn = 1 << 21, // __classPrivateFieldIn (used by the class private field transformation)
|
||||
CreateBinding = 1 << 22, // __createBinding (use by the module transform for (re)exports and namespace imports)
|
||||
FirstEmitHelper = Extends,
|
||||
LastEmitHelper = CreateBinding,
|
||||
|
||||
@@ -7047,7 +7180,7 @@ namespace ts {
|
||||
//
|
||||
|
||||
createModifier<T extends ModifierSyntaxKind>(kind: T): ModifierToken<T>;
|
||||
createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[];
|
||||
createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[] | undefined;
|
||||
|
||||
//
|
||||
// Names
|
||||
@@ -7116,8 +7249,8 @@ namespace ts {
|
||||
updateConstructorTypeNode(node: ConstructorTypeNode, modifiers: readonly Modifier[] | undefined, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode): ConstructorTypeNode;
|
||||
/** @deprecated */
|
||||
updateConstructorTypeNode(node: ConstructorTypeNode, typeParameters: NodeArray<TypeParameterDeclaration> | undefined, parameters: NodeArray<ParameterDeclaration>, type: TypeNode): ConstructorTypeNode;
|
||||
createTypeQueryNode(exprName: EntityName): TypeQueryNode;
|
||||
updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName): TypeQueryNode;
|
||||
createTypeQueryNode(exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode;
|
||||
updateTypeQueryNode(node: TypeQueryNode, exprName: EntityName, typeArguments?: readonly TypeNode[]): TypeQueryNode;
|
||||
createTypeLiteralNode(members: readonly TypeElement[] | undefined): TypeLiteralNode;
|
||||
updateTypeLiteralNode(node: TypeLiteralNode, members: NodeArray<TypeElement>): TypeLiteralNode;
|
||||
createArrayTypeNode(elementType: TypeNode): ArrayTypeNode;
|
||||
@@ -7147,8 +7280,8 @@ namespace ts {
|
||||
updateTypeOperatorNode(node: TypeOperatorNode, type: TypeNode): TypeOperatorNode;
|
||||
createIndexedAccessTypeNode(objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
|
||||
updateIndexedAccessTypeNode(node: IndexedAccessTypeNode, objectType: TypeNode, indexType: TypeNode): IndexedAccessTypeNode;
|
||||
createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode;
|
||||
updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined): MappedTypeNode;
|
||||
createMappedTypeNode(readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray<TypeElement> | undefined): MappedTypeNode;
|
||||
updateMappedTypeNode(node: MappedTypeNode, readonlyToken: ReadonlyKeyword | PlusToken | MinusToken | undefined, typeParameter: TypeParameterDeclaration, nameType: TypeNode | undefined, questionToken: QuestionToken | PlusToken | MinusToken | undefined, type: TypeNode | undefined, members: NodeArray<TypeElement> | undefined): MappedTypeNode;
|
||||
createLiteralTypeNode(literal: LiteralTypeNode["literal"]): LiteralTypeNode;
|
||||
updateLiteralTypeNode(node: LiteralTypeNode, literal: LiteralTypeNode["literal"]): LiteralTypeNode;
|
||||
createTemplateLiteralType(head: TemplateHead, templateSpans: readonly TemplateLiteralTypeSpan[]): TemplateLiteralTypeNode;
|
||||
@@ -7317,26 +7450,30 @@ namespace ts {
|
||||
updateNamespaceExportDeclaration(node: NamespaceExportDeclaration, name: Identifier): NamespaceExportDeclaration;
|
||||
createImportEqualsDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: string | Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
|
||||
updateImportEqualsDeclaration(node: ImportEqualsDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, name: Identifier, moduleReference: ModuleReference): ImportEqualsDeclaration;
|
||||
createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration;
|
||||
updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression): ImportDeclaration;
|
||||
createImportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause?: AssertClause): ImportDeclaration;
|
||||
updateImportDeclaration(node: ImportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, importClause: ImportClause | undefined, moduleSpecifier: Expression, assertClause: AssertClause | undefined): ImportDeclaration;
|
||||
createImportClause(isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause;
|
||||
updateImportClause(node: ImportClause, isTypeOnly: boolean, name: Identifier | undefined, namedBindings: NamedImportBindings | undefined): ImportClause;
|
||||
createAssertClause(elements: NodeArray<AssertEntry>, multiLine?: boolean): AssertClause;
|
||||
updateAssertClause(node: AssertClause, elements: NodeArray<AssertEntry>, multiLine?: boolean): AssertClause;
|
||||
createAssertEntry(name: AssertionKey, value: Expression): AssertEntry;
|
||||
updateAssertEntry(node: AssertEntry, name: AssertionKey, value: Expression): AssertEntry;
|
||||
createNamespaceImport(name: Identifier): NamespaceImport;
|
||||
updateNamespaceImport(node: NamespaceImport, name: Identifier): NamespaceImport;
|
||||
createNamespaceExport(name: Identifier): NamespaceExport;
|
||||
updateNamespaceExport(node: NamespaceExport, name: Identifier): NamespaceExport;
|
||||
createNamedImports(elements: readonly ImportSpecifier[]): NamedImports;
|
||||
updateNamedImports(node: NamedImports, elements: readonly ImportSpecifier[]): NamedImports;
|
||||
createImportSpecifier(propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
|
||||
updateImportSpecifier(node: ImportSpecifier, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
|
||||
createImportSpecifier(isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
|
||||
updateImportSpecifier(node: ImportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ImportSpecifier;
|
||||
createExportAssignment(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isExportEquals: boolean | undefined, expression: Expression): ExportAssignment;
|
||||
updateExportAssignment(node: ExportAssignment, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, expression: Expression): ExportAssignment;
|
||||
createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression): ExportDeclaration;
|
||||
updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined): ExportDeclaration;
|
||||
createExportDeclaration(decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier?: Expression, assertClause?: AssertClause): ExportDeclaration;
|
||||
updateExportDeclaration(node: ExportDeclaration, decorators: readonly Decorator[] | undefined, modifiers: readonly Modifier[] | undefined, isTypeOnly: boolean, exportClause: NamedExportBindings | undefined, moduleSpecifier: Expression | undefined, assertClause: AssertClause | undefined): ExportDeclaration;
|
||||
createNamedExports(elements: readonly ExportSpecifier[]): NamedExports;
|
||||
updateNamedExports(node: NamedExports, elements: readonly ExportSpecifier[]): NamedExports;
|
||||
createExportSpecifier(propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier;
|
||||
updateExportSpecifier(node: ExportSpecifier, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier;
|
||||
createExportSpecifier(isTypeOnly: boolean, propertyName: string | Identifier | undefined, name: string | Identifier): ExportSpecifier;
|
||||
updateExportSpecifier(node: ExportSpecifier, isTypeOnly: boolean, propertyName: Identifier | undefined, name: Identifier): ExportSpecifier;
|
||||
/* @internal*/ createMissingDeclaration(): MissingDeclaration;
|
||||
|
||||
//
|
||||
@@ -7686,9 +7823,10 @@ namespace ts {
|
||||
* Copies only the standard (string-expression) prologue-directives into the target statement-array.
|
||||
* @param source origin statements array
|
||||
* @param target result statements array
|
||||
* @param statementOffset The offset at which to begin the copy.
|
||||
* @param ensureUseStrict boolean determining whether the function need to add prologue-directives
|
||||
*/
|
||||
/* @internal */ copyStandardPrologue(source: readonly Statement[], target: Push<Statement>, ensureUseStrict?: boolean): number;
|
||||
/* @internal */ copyStandardPrologue(source: readonly Statement[], target: Push<Statement>, statementOffset: number | undefined, ensureUseStrict?: boolean): number;
|
||||
/**
|
||||
* Copies only the custom prologue-directives into target statement-array.
|
||||
* @param source origin statements array
|
||||
@@ -7715,7 +7853,7 @@ namespace ts {
|
||||
* - *DO NOT USE THIS* if a more appropriate function is available.
|
||||
*/
|
||||
/* @internal */ cloneNode<T extends Node | undefined>(node: T): T;
|
||||
/* @internal */ updateModifiers<T extends HasModifiers>(node: T, modifiers: readonly Modifier[] | ModifierFlags): T;
|
||||
/* @internal */ updateModifiers<T extends HasModifiers>(node: T, modifiers: readonly Modifier[] | ModifierFlags | undefined): T;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
@@ -7919,6 +8057,8 @@ namespace ts {
|
||||
NoDefaultLib = "no-default-lib",
|
||||
Reference = "reference",
|
||||
Type = "type",
|
||||
TypeResolutionModeRequire = "type-require",
|
||||
TypeResolutionModeImport = "type-import",
|
||||
Lib = "lib",
|
||||
Prepend = "prepend",
|
||||
Text = "text",
|
||||
@@ -7951,7 +8091,7 @@ namespace ts {
|
||||
|
||||
/*@internal*/
|
||||
export interface BundleFileReference extends BundleFileSectionBase {
|
||||
kind: BundleFileSectionKind.Reference | BundleFileSectionKind.Type | BundleFileSectionKind.Lib;
|
||||
kind: BundleFileSectionKind.Reference | BundleFileSectionKind.Type | BundleFileSectionKind.Lib | BundleFileSectionKind.TypeResolutionModeImport | BundleFileSectionKind.TypeResolutionModeRequire;
|
||||
data: string;
|
||||
}
|
||||
|
||||
@@ -8194,6 +8334,7 @@ namespace ts {
|
||||
hasTrailingComment(): boolean;
|
||||
hasTrailingWhitespace(): boolean;
|
||||
getTextPosWithWriteLine?(): number;
|
||||
nonEscapingWrite?(text: string): void;
|
||||
}
|
||||
|
||||
export interface GetEffectiveTypeRootsHost {
|
||||
@@ -8201,6 +8342,11 @@ namespace ts {
|
||||
getCurrentDirectory?(): string;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export interface HasCurrentDirectory {
|
||||
getCurrentDirectory(): string;
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export interface ModuleSpecifierResolutionHost {
|
||||
useCaseSensitiveFileNames?(): boolean;
|
||||
@@ -8211,6 +8357,7 @@ namespace ts {
|
||||
realpath?(path: string): string;
|
||||
getSymlinkCache?(): SymlinkCache;
|
||||
getModuleSpecifierCache?(): ModuleSpecifierCache;
|
||||
getPackageJsonInfoCache?(): PackageJsonInfoCache | undefined;
|
||||
getGlobalTypingsCacheLocation?(): string | undefined;
|
||||
getNearestAncestorDirectoryWithPackageJson?(fileName: string, rootDir?: string): string | undefined;
|
||||
|
||||
@@ -8354,6 +8501,7 @@ namespace ts {
|
||||
ObjectBindingPatternElements = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty,
|
||||
ArrayBindingPatternElements = SingleLine | AllowTrailingComma | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty,
|
||||
ObjectLiteralExpressionProperties = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces | NoSpaceIfEmpty,
|
||||
ImportClauseEntries = PreserveLines | CommaDelimited | SpaceBetweenSiblings | SpaceBetweenBraces | Indented | Braces | NoSpaceIfEmpty,
|
||||
ArrayLiteralExpressionElements = PreserveLines | CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | Indented | SquareBrackets,
|
||||
CommaListElements = CommaDelimited | SpaceBetweenSiblings | SingleLine,
|
||||
CallExpressionArguments = CommaDelimited | SpaceBetweenSiblings | SingleLine | Parenthesis,
|
||||
@@ -8434,7 +8582,8 @@ namespace ts {
|
||||
{ name: "types", optional: true, captureSpan: true },
|
||||
{ name: "lib", optional: true, captureSpan: true },
|
||||
{ name: "path", optional: true, captureSpan: true },
|
||||
{ name: "no-default-lib", optional: true }
|
||||
{ name: "no-default-lib", optional: true },
|
||||
{ name: "resolution-mode", optional: true }
|
||||
],
|
||||
kind: PragmaKindFlags.TripleSlashXML
|
||||
},
|
||||
@@ -8538,6 +8687,7 @@ namespace ts {
|
||||
readonly includeCompletionsWithSnippetText?: boolean;
|
||||
readonly includeAutomaticOptionalChainCompletions?: boolean;
|
||||
readonly includeCompletionsWithInsertText?: boolean;
|
||||
readonly includeCompletionsWithClassMemberSnippets?: boolean;
|
||||
readonly allowIncompleteCompletions?: boolean;
|
||||
readonly importModuleSpecifierPreference?: "shortest" | "project-relative" | "relative" | "non-relative";
|
||||
/** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */
|
||||
@@ -8546,6 +8696,14 @@ namespace ts {
|
||||
readonly providePrefixAndSuffixTextForRename?: boolean;
|
||||
readonly includePackageJsonAutoImports?: "auto" | "on" | "off";
|
||||
readonly provideRefactorNotApplicableReason?: boolean;
|
||||
readonly jsxAttributeCompletionStyle?: "auto" | "braces" | "none";
|
||||
readonly includeInlayParameterNameHints?: "none" | "literals" | "all";
|
||||
readonly includeInlayParameterNameHintsWhenArgumentMatchesName?: boolean;
|
||||
readonly includeInlayFunctionParameterTypeHints?: boolean,
|
||||
readonly includeInlayVariableTypeHints?: boolean;
|
||||
readonly includeInlayPropertyDeclarationTypeHints?: boolean;
|
||||
readonly includeInlayFunctionLikeReturnTypeHints?: boolean;
|
||||
readonly includeInlayEnumMemberValueHints?: boolean;
|
||||
}
|
||||
|
||||
/** Represents a bigint literal value without requiring bigint support */
|
||||
|
||||
+328
-160
@@ -20,19 +20,8 @@ namespace ts {
|
||||
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 getDeclarationsOfKind<T extends Declaration>(symbol: Symbol, kind: T["kind"]): T[] {
|
||||
return filter(symbol.declarations || emptyArray, d => d.kind === kind) as T[];
|
||||
}
|
||||
|
||||
export function createSymbolTable(symbols?: readonly Symbol[]): SymbolTable {
|
||||
@@ -169,24 +158,24 @@ namespace ts {
|
||||
return node.end - node.pos;
|
||||
}
|
||||
|
||||
export function getResolvedModule(sourceFile: SourceFile | undefined, moduleNameText: string): ResolvedModuleFull | undefined {
|
||||
return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
|
||||
export function getResolvedModule(sourceFile: SourceFile | undefined, moduleNameText: string, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): ResolvedModuleFull | undefined {
|
||||
return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText, mode);
|
||||
}
|
||||
|
||||
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void {
|
||||
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull, mode: ModuleKind.CommonJS | ModuleKind.ESNext | undefined): void {
|
||||
if (!sourceFile.resolvedModules) {
|
||||
sourceFile.resolvedModules = new Map<string, ResolvedModuleFull>();
|
||||
sourceFile.resolvedModules = createModeAwareCache();
|
||||
}
|
||||
|
||||
sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
|
||||
sourceFile.resolvedModules.set(moduleNameText, mode, resolvedModule);
|
||||
}
|
||||
|
||||
export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective?: ResolvedTypeReferenceDirective): void {
|
||||
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
|
||||
sourceFile.resolvedTypeReferenceDirectiveNames = new Map<string, ResolvedTypeReferenceDirective | undefined>();
|
||||
sourceFile.resolvedTypeReferenceDirectiveNames = createModeAwareCache();
|
||||
}
|
||||
|
||||
sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
|
||||
sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, /*mode*/ undefined, resolvedTypeReferenceDirective);
|
||||
}
|
||||
|
||||
export function projectReferenceIsEqualTo(oldRef: ProjectReference, newRef: ProjectReference) {
|
||||
@@ -207,9 +196,12 @@ namespace ts {
|
||||
return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
|
||||
}
|
||||
|
||||
export function packageIdToString({ name, subModuleName, version }: PackageId): string {
|
||||
const fullName = subModuleName ? `${name}/${subModuleName}` : name;
|
||||
return `${fullName}@${version}`;
|
||||
export function packageIdToPackageName({ name, subModuleName }: PackageId): string {
|
||||
return subModuleName ? `${name}/${subModuleName}` : name;
|
||||
}
|
||||
|
||||
export function packageIdToString(packageId: PackageId): string {
|
||||
return `${packageIdToPackageName(packageId)}@${packageId.version}`;
|
||||
}
|
||||
|
||||
export function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirective, newResolution: ResolvedTypeReferenceDirective): boolean {
|
||||
@@ -219,15 +211,20 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function hasChangesInResolutions<T>(
|
||||
names: readonly string[],
|
||||
names: readonly string[] | readonly FileReference[],
|
||||
newResolutions: readonly T[],
|
||||
oldResolutions: ReadonlyESMap<string, T> | undefined,
|
||||
oldResolutions: ModeAwareCache<T> | undefined,
|
||||
oldSourceFile: SourceFile | undefined,
|
||||
comparer: (oldResolution: T, newResolution: T) => boolean): boolean {
|
||||
Debug.assert(names.length === newResolutions.length);
|
||||
|
||||
for (let i = 0; i < names.length; i++) {
|
||||
const newResolution = newResolutions[i];
|
||||
const oldResolution = oldResolutions && oldResolutions.get(names[i]);
|
||||
const entry = names[i];
|
||||
// We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
|
||||
const name = !isString(entry) ? entry.fileName.toLowerCase() : entry;
|
||||
const mode = !isString(entry) ? getModeForFileReference(entry, oldSourceFile?.impliedNodeFormat) : oldSourceFile && getModeForResolutionAtIndex(oldSourceFile, i);
|
||||
const oldResolution = oldResolutions && oldResolutions.get(name, mode);
|
||||
const changed =
|
||||
oldResolution
|
||||
? !newResolution || !comparer(oldResolution, newResolution)
|
||||
@@ -278,6 +275,10 @@ namespace ts {
|
||||
return getSourceFileOfNode(module.valueDeclaration || getNonAugmentationDeclaration(module));
|
||||
}
|
||||
|
||||
export function isPlainJsFile(file: SourceFile | undefined, checkJs: boolean | undefined): boolean {
|
||||
return !!file && (file.scriptKind === ScriptKind.JS || file.scriptKind === ScriptKind.JSX) && !file.checkJsDirective && checkJs === undefined;
|
||||
}
|
||||
|
||||
export function isStatementWithLocals(node: Node) {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.Block:
|
||||
@@ -605,6 +606,7 @@ namespace ts {
|
||||
AsyncIterableIterator: emptyArray,
|
||||
AsyncGenerator: emptyArray,
|
||||
AsyncGeneratorFunction: emptyArray,
|
||||
NumberFormat: ["formatToParts"]
|
||||
},
|
||||
es2019: {
|
||||
Array: ["flat", "flatMap"],
|
||||
@@ -626,8 +628,22 @@ namespace ts {
|
||||
PromiseConstructor: ["any"],
|
||||
String: ["replaceAll"]
|
||||
},
|
||||
esnext: {
|
||||
NumberFormat: ["formatToParts"]
|
||||
es2022: {
|
||||
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"],
|
||||
Error: ["cause"]
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -791,8 +807,12 @@ namespace ts {
|
||||
return symbol.declarations?.find(d => !isExternalModuleAugmentation(d) && !(isModuleDeclaration(d) && isGlobalScopeAugmentation(d)));
|
||||
}
|
||||
|
||||
function isCommonJSContainingModuleKind(kind: ModuleKind) {
|
||||
return kind === ModuleKind.CommonJS || kind === ModuleKind.Node12 || kind === ModuleKind.NodeNext;
|
||||
}
|
||||
|
||||
export function isEffectiveExternalModule(node: SourceFile, compilerOptions: CompilerOptions) {
|
||||
return isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
|
||||
return isExternalModule(node) || compilerOptions.isolatedModules || (isCommonJSContainingModuleKind(getEmitModuleKind(compilerOptions)) && !!node.commonJsModuleIndicator);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1063,6 +1083,15 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
export function createDiagnosticMessageChainFromDiagnostic(diagnostic: DiagnosticRelatedInformation): DiagnosticMessageChain {
|
||||
return typeof diagnostic.messageText === "string" ? {
|
||||
code: diagnostic.code,
|
||||
category: diagnostic.category,
|
||||
messageText: diagnostic.messageText,
|
||||
next: (diagnostic as DiagnosticMessageChain).next,
|
||||
} : diagnostic.messageText;
|
||||
}
|
||||
|
||||
export function createDiagnosticForRange(sourceFile: SourceFile, range: TextRange, message: DiagnosticMessage): DiagnosticWithLocation {
|
||||
return {
|
||||
file: sourceFile,
|
||||
@@ -1239,7 +1268,8 @@ namespace ts {
|
||||
node.kind === SyntaxKind.FunctionExpression ||
|
||||
node.kind === SyntaxKind.ArrowFunction ||
|
||||
node.kind === SyntaxKind.ParenthesizedExpression ||
|
||||
node.kind === SyntaxKind.VariableDeclaration) ?
|
||||
node.kind === SyntaxKind.VariableDeclaration ||
|
||||
node.kind === SyntaxKind.ExportSpecifier) ?
|
||||
concatenate(getTrailingCommentRanges(text, node.pos), getLeadingCommentRanges(text, node.pos)) :
|
||||
getLeadingCommentRanges(text, node.pos);
|
||||
// True if the comment starts with '/**' but not if it is '/**/'
|
||||
@@ -1274,7 +1304,7 @@ namespace ts {
|
||||
case SyntaxKind.VoidKeyword:
|
||||
return node.parent.kind !== SyntaxKind.VoidExpression;
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
|
||||
return isHeritageClause(node.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(node);
|
||||
case SyntaxKind.TypeParameter:
|
||||
return node.parent.kind === SyntaxKind.MappedType || node.parent.kind === SyntaxKind.InferType;
|
||||
|
||||
@@ -1314,7 +1344,7 @@ namespace ts {
|
||||
}
|
||||
switch (parent.kind) {
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
|
||||
return isHeritageClause(parent.parent) && !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
|
||||
case SyntaxKind.TypeParameter:
|
||||
return node === (parent as TypeParameterDeclaration).constraint;
|
||||
case SyntaxKind.JSDocTemplateTag:
|
||||
@@ -1664,6 +1694,34 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns Whether the node creates a new 'this' scope for its children.
|
||||
*/
|
||||
export function isThisContainerOrFunctionBlock(node: Node): boolean {
|
||||
switch (node.kind) {
|
||||
// Arrow functions use the same scope, but may do so in a "delayed" manner
|
||||
// For example, `const getThis = () => this` may be before a super() call in a derived constructor
|
||||
case SyntaxKind.ArrowFunction:
|
||||
case SyntaxKind.FunctionDeclaration:
|
||||
case SyntaxKind.FunctionExpression:
|
||||
case SyntaxKind.PropertyDeclaration:
|
||||
return true;
|
||||
case SyntaxKind.Block:
|
||||
switch (node.parent.kind) {
|
||||
case SyntaxKind.Constructor:
|
||||
case SyntaxKind.MethodDeclaration:
|
||||
case SyntaxKind.GetAccessor:
|
||||
case SyntaxKind.SetAccessor:
|
||||
// Object properties can have computed names; only method-like bodies start a new scope
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isInTopLevelContext(node: Node) {
|
||||
// The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
|
||||
if (isIdentifier(node) && (isClassDeclaration(node.parent) || isFunctionDeclaration(node.parent)) && node.parent.name === node) {
|
||||
@@ -1949,6 +2007,8 @@ namespace ts {
|
||||
node = node.parent;
|
||||
}
|
||||
return node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node);
|
||||
case SyntaxKind.PrivateIdentifier:
|
||||
return isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === SyntaxKind.InKeyword;
|
||||
case SyntaxKind.Identifier:
|
||||
if (node.parent.kind === SyntaxKind.TypeQuery || isJSDocLinkLike(node.parent) || isJSDocNameReference(node.parent) || isJSDocMemberName(node.parent) || isJSXTagName(node)) {
|
||||
return true;
|
||||
@@ -2010,7 +2070,7 @@ namespace ts {
|
||||
case SyntaxKind.SpreadAssignment:
|
||||
return true;
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
return (parent as ExpressionWithTypeArguments).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
|
||||
return (parent as ExpressionWithTypeArguments).expression === node && !isPartOfTypeNode(parent);
|
||||
case SyntaxKind.ShorthandPropertyAssignment:
|
||||
return (parent as ShorthandPropertyAssignment).objectAssignmentInitializer === node;
|
||||
default:
|
||||
@@ -2039,7 +2099,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getExternalModuleRequireArgument(node: Node) {
|
||||
return isRequireVariableDeclaration(node) && (getLeftmostAccessExpression(node.initializer) as CallExpression).arguments[0] as StringLiteral;
|
||||
return isVariableDeclarationInitializedToBareOrAccessedRequire(node) && (getLeftmostAccessExpression(node.initializer) as CallExpression).arguments[0] as StringLiteral;
|
||||
}
|
||||
|
||||
export function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration {
|
||||
@@ -2106,17 +2166,30 @@ namespace ts {
|
||||
* Returns true if the node is a VariableDeclaration initialized to a require call (see `isRequireCall`).
|
||||
* This function does not test if the node is in a JavaScript file or not.
|
||||
*/
|
||||
export function isRequireVariableDeclaration(node: Node): node is RequireVariableDeclaration {
|
||||
export function isVariableDeclarationInitializedToRequire(node: Node): node is VariableDeclarationInitializedTo<RequireOrImportCall> {
|
||||
return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link isVariableDeclarationInitializedToRequire} but allows things like `require("...").foo.bar` or `require("...")["baz"]`.
|
||||
*/
|
||||
export function isVariableDeclarationInitializedToBareOrAccessedRequire(node: Node): node is VariableDeclarationInitializedTo<RequireOrImportCall | AccessExpression> {
|
||||
return isVariableDeclarationInitializedWithRequireHelper(node, /*allowAccessedRequire*/ true);
|
||||
}
|
||||
|
||||
function isVariableDeclarationInitializedWithRequireHelper(node: Node, allowAccessedRequire: boolean) {
|
||||
if (node.kind === SyntaxKind.BindingElement) {
|
||||
node = node.parent.parent;
|
||||
}
|
||||
return isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), /*requireStringLiteralLikeArgument*/ true);
|
||||
return isVariableDeclaration(node) &&
|
||||
!!node.initializer &&
|
||||
isRequireCall(allowAccessedRequire ? getLeftmostAccessExpression(node.initializer) : node.initializer, /*requireStringLiteralLikeArgument*/ true);
|
||||
}
|
||||
|
||||
export function isRequireVariableStatement(node: Node): node is RequireVariableStatement {
|
||||
return isVariableStatement(node)
|
||||
&& node.declarationList.declarations.length > 0
|
||||
&& every(node.declarationList.declarations, decl => isRequireVariableDeclaration(decl));
|
||||
&& every(node.declarationList.declarations, decl => isVariableDeclarationInitializedToRequire(decl));
|
||||
}
|
||||
|
||||
export function isSingleOrDoubleQuote(charCode: number) {
|
||||
@@ -2212,7 +2285,7 @@ namespace ts {
|
||||
const e = isBinaryExpression(initializer)
|
||||
&& (initializer.operatorToken.kind === SyntaxKind.BarBarToken || initializer.operatorToken.kind === SyntaxKind.QuestionQuestionToken)
|
||||
&& getExpandoInitializer(initializer.right, isPrototypeAssignment);
|
||||
if (e && isSameEntityName(name, (initializer as BinaryExpression).left)) {
|
||||
if (e && isSameEntityName(name, initializer.left)) {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -2445,7 +2518,7 @@ namespace ts {
|
||||
return expr.right;
|
||||
}
|
||||
|
||||
export function isPrototypePropertyAssignment(node: Node): boolean {
|
||||
export function isPrototypePropertyAssignment(node: Node): node is BinaryExpression {
|
||||
return isBinaryExpression(node) && getAssignmentDeclarationKind(node) === AssignmentDeclarationKind.PrototypeProperty;
|
||||
}
|
||||
|
||||
@@ -3154,7 +3227,7 @@ namespace ts {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function isKeyword(token: SyntaxKind): boolean {
|
||||
export function isKeyword(token: SyntaxKind): token is KeywordSyntaxKind {
|
||||
return SyntaxKind.FirstKeyword <= token && token <= SyntaxKind.LastKeyword;
|
||||
}
|
||||
|
||||
@@ -3339,7 +3412,7 @@ namespace ts {
|
||||
return node.escapedText === "push" || node.escapedText === "unshift";
|
||||
}
|
||||
|
||||
export function isParameterDeclaration(node: VariableLikeDeclaration) {
|
||||
export function isParameterDeclaration(node: VariableLikeDeclaration): boolean {
|
||||
const root = getRootDeclaration(node);
|
||||
return root.kind === SyntaxKind.Parameter;
|
||||
}
|
||||
@@ -3706,6 +3779,7 @@ namespace ts {
|
||||
case SyntaxKind.ThisKeyword:
|
||||
case SyntaxKind.SuperKeyword:
|
||||
case SyntaxKind.Identifier:
|
||||
case SyntaxKind.PrivateIdentifier:
|
||||
case SyntaxKind.NullKeyword:
|
||||
case SyntaxKind.TrueKeyword:
|
||||
case SyntaxKind.FalseKeyword:
|
||||
@@ -4270,7 +4344,15 @@ namespace ts {
|
||||
const path = outputDir
|
||||
? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
|
||||
: fileName;
|
||||
return removeFileExtension(path) + Extension.Dts;
|
||||
const declarationExtension = getDeclarationEmitExtensionForPath(path);
|
||||
return removeFileExtension(path) + declarationExtension;
|
||||
}
|
||||
|
||||
export function getDeclarationEmitExtensionForPath(path: string) {
|
||||
return fileExtensionIsOneOf(path, [Extension.Mjs, Extension.Mts]) ? Extension.Dmts :
|
||||
fileExtensionIsOneOf(path, [Extension.Cjs, Extension.Cts]) ? Extension.Dcts :
|
||||
fileExtensionIsOneOf(path, [Extension.Json]) ? `.json.d.ts` : // Drive-by redefinition of json declaration file output name so if it's ever enabled, it behaves well
|
||||
Extension.Dts;
|
||||
}
|
||||
|
||||
export function outFile(options: CompilerOptions) {
|
||||
@@ -5842,7 +5924,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// eslint-disable-next-line prefer-const
|
||||
export let objectAllocator: ObjectAllocator = {
|
||||
export const objectAllocator: ObjectAllocator = {
|
||||
getNodeConstructor: () => Node as any,
|
||||
getTokenConstructor: () => Token as any,
|
||||
getIdentifierConstructor: () => Identifier as any,
|
||||
@@ -5855,20 +5937,29 @@ namespace ts {
|
||||
};
|
||||
|
||||
export function setObjectAllocator(alloc: ObjectAllocator) {
|
||||
objectAllocator = alloc;
|
||||
Object.assign(objectAllocator, alloc);
|
||||
}
|
||||
|
||||
export function formatStringFromArgs(text: string, args: ArrayLike<string | number>, baseIndex = 0): string {
|
||||
return text.replace(/{(\d+)}/g, (_match, index: string) => "" + Debug.checkDefined(args[+index + baseIndex]));
|
||||
}
|
||||
|
||||
export let localizedDiagnosticMessages: MapLike<string> | undefined;
|
||||
let localizedDiagnosticMessages: MapLike<string> | undefined;
|
||||
|
||||
/* @internal */
|
||||
export function setLocalizedDiagnosticMessages(messages: typeof localizedDiagnosticMessages) {
|
||||
localizedDiagnosticMessages = messages;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
// If the localized messages json is unset, and if given function use it to set the json
|
||||
|
||||
export function maybeSetLocalizedDiagnosticMessages(getMessages: undefined | (() => typeof localizedDiagnosticMessages)) {
|
||||
if (!localizedDiagnosticMessages && getMessages) {
|
||||
localizedDiagnosticMessages = getMessages();
|
||||
}
|
||||
}
|
||||
|
||||
export function getLocaleSpecificMessage(message: DiagnosticMessage) {
|
||||
return localizedDiagnosticMessages && localizedDiagnosticMessages[message.key] || message.message;
|
||||
}
|
||||
@@ -6110,8 +6201,11 @@ namespace ts {
|
||||
return scriptKind === ScriptKind.TSX || scriptKind === ScriptKind.JSX || scriptKind === ScriptKind.JS || scriptKind === ScriptKind.JSON ? LanguageVariant.JSX : LanguageVariant.Standard;
|
||||
}
|
||||
|
||||
export function getEmitScriptTarget(compilerOptions: CompilerOptions) {
|
||||
return compilerOptions.target || ScriptTarget.ES3;
|
||||
export function getEmitScriptTarget(compilerOptions: {module?: CompilerOptions["module"], target?: CompilerOptions["target"]}) {
|
||||
return compilerOptions.target ||
|
||||
(compilerOptions.module === ModuleKind.Node12 && ScriptTarget.ES2020) ||
|
||||
(compilerOptions.module === ModuleKind.NodeNext && ScriptTarget.ESNext) ||
|
||||
ScriptTarget.ES3;
|
||||
}
|
||||
|
||||
export function getEmitModuleKind(compilerOptions: {module?: CompilerOptions["module"], target?: CompilerOptions["target"]}) {
|
||||
@@ -6123,7 +6217,20 @@ namespace ts {
|
||||
export function getEmitModuleResolutionKind(compilerOptions: CompilerOptions) {
|
||||
let moduleResolution = compilerOptions.moduleResolution;
|
||||
if (moduleResolution === undefined) {
|
||||
moduleResolution = getEmitModuleKind(compilerOptions) === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
|
||||
switch (getEmitModuleKind(compilerOptions)) {
|
||||
case ModuleKind.CommonJS:
|
||||
moduleResolution = ModuleResolutionKind.NodeJs;
|
||||
break;
|
||||
case ModuleKind.Node12:
|
||||
moduleResolution = ModuleResolutionKind.Node12;
|
||||
break;
|
||||
case ModuleKind.NodeNext:
|
||||
moduleResolution = ModuleResolutionKind.NodeNext;
|
||||
break;
|
||||
default:
|
||||
moduleResolution = ModuleResolutionKind.Classic;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return moduleResolution;
|
||||
}
|
||||
@@ -6134,7 +6241,10 @@ namespace ts {
|
||||
case ModuleKind.AMD:
|
||||
case ModuleKind.ES2015:
|
||||
case ModuleKind.ES2020:
|
||||
case ModuleKind.ES2022:
|
||||
case ModuleKind.ESNext:
|
||||
case ModuleKind.Node12:
|
||||
case ModuleKind.NodeNext:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
@@ -6153,11 +6263,23 @@ namespace ts {
|
||||
return !!(getEmitDeclarations(options) && options.declarationMap);
|
||||
}
|
||||
|
||||
export function getESModuleInterop(compilerOptions: CompilerOptions) {
|
||||
if (compilerOptions.esModuleInterop !== undefined) {
|
||||
return compilerOptions.esModuleInterop;
|
||||
}
|
||||
switch (getEmitModuleKind(compilerOptions)) {
|
||||
case ModuleKind.Node12:
|
||||
case ModuleKind.NodeNext:
|
||||
return true;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getAllowSyntheticDefaultImports(compilerOptions: CompilerOptions) {
|
||||
const moduleKind = getEmitModuleKind(compilerOptions);
|
||||
return compilerOptions.allowSyntheticDefaultImports !== undefined
|
||||
? compilerOptions.allowSyntheticDefaultImports
|
||||
: compilerOptions.esModuleInterop ||
|
||||
: getESModuleInterop(compilerOptions) ||
|
||||
moduleKind === ModuleKind.System;
|
||||
}
|
||||
|
||||
@@ -6193,7 +6315,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getUseDefineForClassFields(compilerOptions: CompilerOptions): boolean {
|
||||
return compilerOptions.useDefineForClassFields === undefined ? compilerOptions.target === ScriptTarget.ESNext : compilerOptions.useDefineForClassFields;
|
||||
return compilerOptions.useDefineForClassFields === undefined ? getEmitScriptTarget(compilerOptions) >= ScriptTarget.ES2022 : compilerOptions.useDefineForClassFields;
|
||||
}
|
||||
|
||||
export function compilerOptionsAffectSemanticDiagnostics(newOptions: CompilerOptions, oldOptions: CompilerOptions): boolean {
|
||||
@@ -6260,15 +6382,13 @@ namespace ts {
|
||||
getSymlinkedFiles(): ReadonlyESMap<Path, string> | undefined;
|
||||
setSymlinkedDirectory(symlink: string, real: SymlinkedDirectory | false): void;
|
||||
setSymlinkedFile(symlinkPath: Path, real: string): void;
|
||||
/*@internal*/
|
||||
setSymlinkedDirectoryFromSymlinkedFile(symlink: string, real: string): void;
|
||||
/**
|
||||
* @internal
|
||||
* Uses resolvedTypeReferenceDirectives from program instead of from files, since files
|
||||
* don't include automatic type reference directives. Must be called only when
|
||||
* `hasProcessedResolutions` returns false (once per cache instance).
|
||||
*/
|
||||
setSymlinksFromResolutions(files: readonly SourceFile[], typeReferenceDirectives: ReadonlyESMap<string, ResolvedTypeReferenceDirective | undefined> | undefined): void;
|
||||
setSymlinksFromResolutions(files: readonly SourceFile[], typeReferenceDirectives: ModeAwareCache<ResolvedTypeReferenceDirective | undefined> | undefined): void;
|
||||
/**
|
||||
* @internal
|
||||
* Whether `setSymlinksFromResolutions` has already been called.
|
||||
@@ -6299,16 +6419,6 @@ namespace ts {
|
||||
(symlinkedDirectories || (symlinkedDirectories = new Map())).set(symlinkPath, real);
|
||||
}
|
||||
},
|
||||
setSymlinkedDirectoryFromSymlinkedFile(symlink, real) {
|
||||
this.setSymlinkedFile(toPath(symlink, cwd, getCanonicalFileName), real);
|
||||
const [commonResolved, commonOriginal] = guessDirectorySymlink(real, symlink, cwd, getCanonicalFileName) || emptyArray;
|
||||
if (commonResolved && commonOriginal) {
|
||||
this.setSymlinkedDirectory(commonOriginal, {
|
||||
real: commonResolved,
|
||||
realPath: toPath(commonResolved, cwd, getCanonicalFileName),
|
||||
});
|
||||
}
|
||||
},
|
||||
setSymlinksFromResolutions(files, typeReferenceDirectives) {
|
||||
Debug.assert(!hasProcessedResolutions);
|
||||
hasProcessedResolutions = true;
|
||||
@@ -6337,9 +6447,12 @@ namespace ts {
|
||||
const aParts = getPathComponents(getNormalizedAbsolutePath(a, cwd));
|
||||
const bParts = getPathComponents(getNormalizedAbsolutePath(b, cwd));
|
||||
let isDirectory = false;
|
||||
while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
|
||||
while (
|
||||
aParts.length >= 2 && bParts.length >= 2 &&
|
||||
!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
|
||||
!isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
|
||||
getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
|
||||
getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])
|
||||
) {
|
||||
aParts.pop();
|
||||
bParts.pop();
|
||||
isDirectory = true;
|
||||
@@ -6349,8 +6462,8 @@ namespace ts {
|
||||
|
||||
// KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
|
||||
// ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
|
||||
function isNodeModulesOrScopedPackageDirectory(s: string, getCanonicalFileName: GetCanonicalFileName): boolean {
|
||||
return getCanonicalFileName(s) === "node_modules" || startsWith(s, "@");
|
||||
function isNodeModulesOrScopedPackageDirectory(s: string | undefined, getCanonicalFileName: GetCanonicalFileName): boolean {
|
||||
return s !== undefined && (getCanonicalFileName(s) === "node_modules" || startsWith(s, "@"));
|
||||
}
|
||||
|
||||
function stripLeadingDirectorySeparator(s: string): string | undefined {
|
||||
@@ -6574,7 +6687,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/** @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);
|
||||
currentDirectory = normalizePath(currentDirectory);
|
||||
|
||||
@@ -6590,9 +6703,7 @@ namespace ts {
|
||||
const visited = new Map<string, true>();
|
||||
const toCanonical = createGetCanonicalFileName(useCaseSensitiveFileNames);
|
||||
for (const basePath of patterns.basePaths) {
|
||||
if (directoryExists(basePath)) {
|
||||
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
|
||||
}
|
||||
visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth);
|
||||
}
|
||||
|
||||
return flatten(results);
|
||||
@@ -6695,10 +6806,14 @@ namespace ts {
|
||||
const ext = fileName.substr(fileName.lastIndexOf("."));
|
||||
switch (ext.toLowerCase()) {
|
||||
case Extension.Js:
|
||||
case Extension.Cjs:
|
||||
case Extension.Mjs:
|
||||
return ScriptKind.JS;
|
||||
case Extension.Jsx:
|
||||
return ScriptKind.JSX;
|
||||
case Extension.Ts:
|
||||
case Extension.Cts:
|
||||
case Extension.Mts:
|
||||
return ScriptKind.TS;
|
||||
case Extension.Tsx:
|
||||
return ScriptKind.TSX;
|
||||
@@ -6710,39 +6825,44 @@ namespace ts {
|
||||
}
|
||||
|
||||
/**
|
||||
* List of supported extensions in order of file resolution precedence.
|
||||
* Groups of supported extensions in order of file resolution precedence. (eg, TS > TSX > DTS and seperately, CTS > DCTS)
|
||||
*/
|
||||
export const supportedTSExtensions: readonly Extension[] = [Extension.Ts, Extension.Tsx, Extension.Dts];
|
||||
export const supportedTSExtensionsWithJson: readonly Extension[] = [Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Json];
|
||||
export const supportedTSExtensions: readonly Extension[][] = [[Extension.Ts, Extension.Tsx, Extension.Dts], [Extension.Cts, Extension.Dcts], [Extension.Mts, Extension.Dmts]];
|
||||
export const supportedTSExtensionsFlat: readonly Extension[] = flatten(supportedTSExtensions);
|
||||
const supportedTSExtensionsWithJson: readonly Extension[][] = [...supportedTSExtensions, [Extension.Json]];
|
||||
/** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
|
||||
export const supportedTSExtensionsForExtractExtension: readonly Extension[] = [Extension.Dts, Extension.Ts, Extension.Tsx];
|
||||
export const supportedJSExtensions: readonly Extension[] = [Extension.Js, Extension.Jsx];
|
||||
export const supportedJSAndJsonExtensions: readonly Extension[] = [Extension.Js, Extension.Jsx, Extension.Json];
|
||||
const allSupportedExtensions: readonly Extension[] = [...supportedTSExtensions, ...supportedJSExtensions];
|
||||
const allSupportedExtensionsWithJson: readonly Extension[] = [...supportedTSExtensions, ...supportedJSExtensions, Extension.Json];
|
||||
const supportedTSExtensionsForExtractExtension: readonly Extension[] = [Extension.Dts, Extension.Dcts, Extension.Dmts, Extension.Cts, Extension.Mts, Extension.Ts, Extension.Tsx, Extension.Cts, Extension.Mts];
|
||||
export const supportedJSExtensions: readonly Extension[][] = [[Extension.Js, Extension.Jsx], [Extension.Mjs], [Extension.Cjs]];
|
||||
export const supportedJSExtensionsFlat: readonly Extension[] = flatten(supportedJSExtensions);
|
||||
const allSupportedExtensions: readonly Extension[][] = [[Extension.Ts, Extension.Tsx, Extension.Dts, Extension.Js, Extension.Jsx], [Extension.Cts, Extension.Dcts, Extension.Cjs], [Extension.Mts, Extension.Dmts, Extension.Mjs]];
|
||||
const allSupportedExtensionsWithJson: readonly Extension[][] = [...allSupportedExtensions, [Extension.Json]];
|
||||
|
||||
export function getSupportedExtensions(options?: CompilerOptions): readonly Extension[];
|
||||
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): readonly string[];
|
||||
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): readonly string[] {
|
||||
export function getSupportedExtensions(options?: CompilerOptions): readonly Extension[][];
|
||||
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): readonly string[][];
|
||||
export function getSupportedExtensions(options?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]): readonly string[][] {
|
||||
const needJsExtensions = options && getAllowJSCompilerOption(options);
|
||||
|
||||
if (!extraFileExtensions || extraFileExtensions.length === 0) {
|
||||
return needJsExtensions ? allSupportedExtensions : supportedTSExtensions;
|
||||
}
|
||||
|
||||
const builtins = needJsExtensions ? allSupportedExtensions : supportedTSExtensions;
|
||||
const flatBuiltins = flatten(builtins);
|
||||
const extensions = [
|
||||
...needJsExtensions ? allSupportedExtensions : supportedTSExtensions,
|
||||
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined)
|
||||
...builtins,
|
||||
...mapDefined(extraFileExtensions, x => x.scriptKind === ScriptKind.Deferred || needJsExtensions && isJSLike(x.scriptKind) && flatBuiltins.indexOf(x.extension as Extension) === -1 ? [x.extension] : undefined)
|
||||
];
|
||||
|
||||
return deduplicate<string>(extensions, equateStringsCaseSensitive, compareStringsCaseSensitive);
|
||||
return extensions;
|
||||
}
|
||||
|
||||
export function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: readonly string[]): readonly string[] {
|
||||
export function getSupportedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: readonly Extension[][]): readonly Extension[][];
|
||||
export function getSupportedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: readonly string[][]): readonly string[][];
|
||||
export function getSupportedExtensionsWithJsonIfResolveJsonModule(options: CompilerOptions | undefined, supportedExtensions: readonly string[][]): readonly string[][] {
|
||||
if (!options || !options.resolveJsonModule) return supportedExtensions;
|
||||
if (supportedExtensions === allSupportedExtensions) return allSupportedExtensionsWithJson;
|
||||
if (supportedExtensions === supportedTSExtensions) return supportedTSExtensionsWithJson;
|
||||
return [...supportedExtensions, Extension.Json];
|
||||
return [...supportedExtensions, [Extension.Json]];
|
||||
}
|
||||
|
||||
function isJSLike(scriptKind: ScriptKind | undefined): boolean {
|
||||
@@ -6750,18 +6870,18 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function hasJSFileExtension(fileName: string): boolean {
|
||||
return some(supportedJSExtensions, extension => fileExtensionIs(fileName, extension));
|
||||
return some(supportedJSExtensionsFlat, extension => fileExtensionIs(fileName, extension));
|
||||
}
|
||||
|
||||
export function hasTSFileExtension(fileName: string): boolean {
|
||||
return some(supportedTSExtensions, extension => fileExtensionIs(fileName, extension));
|
||||
return some(supportedTSExtensionsFlat, extension => fileExtensionIs(fileName, extension));
|
||||
}
|
||||
|
||||
export function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions, extraFileExtensions?: readonly FileExtensionInfo[]) {
|
||||
if (!fileName) return false;
|
||||
|
||||
const supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
|
||||
for (const extension of getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions)) {
|
||||
for (const extension of flatten(getSupportedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions))) {
|
||||
if (fileExtensionIs(fileName, extension)) {
|
||||
return true;
|
||||
}
|
||||
@@ -6781,59 +6901,7 @@ namespace ts {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extension boundaries by priority. Lower numbers indicate higher priorities, and are
|
||||
* aligned to the offset of the highest priority extension in the
|
||||
* allSupportedExtensions array.
|
||||
*/
|
||||
export const enum ExtensionPriority {
|
||||
TypeScriptFiles = 0,
|
||||
DeclarationAndJavaScriptFiles = 2,
|
||||
|
||||
Highest = TypeScriptFiles,
|
||||
Lowest = DeclarationAndJavaScriptFiles,
|
||||
}
|
||||
|
||||
export function getExtensionPriority(path: string, supportedExtensions: readonly string[]): ExtensionPriority {
|
||||
for (let i = supportedExtensions.length - 1; i >= 0; i--) {
|
||||
if (fileExtensionIs(path, supportedExtensions[i])) {
|
||||
return adjustExtensionPriority(i as ExtensionPriority, supportedExtensions);
|
||||
}
|
||||
}
|
||||
|
||||
// If its not in the list of supported extensions, this is likely a
|
||||
// TypeScript file with a non-ts extension
|
||||
return ExtensionPriority.Highest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjusts an extension priority to be the highest priority within the same range.
|
||||
*/
|
||||
export function adjustExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: readonly string[]): ExtensionPriority {
|
||||
if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) {
|
||||
return ExtensionPriority.TypeScriptFiles;
|
||||
}
|
||||
else if (extensionPriority < supportedExtensions.length) {
|
||||
return ExtensionPriority.DeclarationAndJavaScriptFiles;
|
||||
}
|
||||
else {
|
||||
return supportedExtensions.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the next lowest extension priority for a given priority.
|
||||
*/
|
||||
export function getNextLowestExtensionPriority(extensionPriority: ExtensionPriority, supportedExtensions: readonly string[]): ExtensionPriority {
|
||||
if (extensionPriority < ExtensionPriority.DeclarationAndJavaScriptFiles) {
|
||||
return ExtensionPriority.DeclarationAndJavaScriptFiles;
|
||||
}
|
||||
else {
|
||||
return supportedExtensions.length;
|
||||
}
|
||||
}
|
||||
|
||||
const extensionsToRemove = [Extension.Dts, Extension.Ts, Extension.Js, Extension.Tsx, Extension.Jsx, Extension.Json];
|
||||
const extensionsToRemove = [Extension.Dts, Extension.Dmts, Extension.Dcts, Extension.Mjs, Extension.Mts, Extension.Cjs, Extension.Cts, Extension.Ts, Extension.Js, Extension.Tsx, Extension.Jsx, Extension.Json];
|
||||
export function removeFileExtension(path: string): string {
|
||||
for (const ext of extensionsToRemove) {
|
||||
const extensionless = tryRemoveExtension(path, ext);
|
||||
@@ -6885,7 +6953,7 @@ namespace ts {
|
||||
|
||||
/** True if an extension is one of the supported TypeScript extensions. */
|
||||
export function extensionIsTS(ext: Extension): boolean {
|
||||
return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts;
|
||||
return ext === Extension.Ts || ext === Extension.Tsx || ext === Extension.Dts || ext === Extension.Cts || ext === Extension.Mts || ext === Extension.Dmts || ext === Extension.Dcts;
|
||||
}
|
||||
|
||||
export function resolutionExtensionIsTSOrJson(ext: Extension) {
|
||||
@@ -6975,18 +7043,6 @@ namespace ts {
|
||||
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 {
|
||||
return { pos: getTokenPosOfNode(node), end: node.end };
|
||||
}
|
||||
@@ -7098,10 +7154,6 @@ namespace ts {
|
||||
|| !(isExpressionNode(useSite) || isShorthandPropertyNameUseSite(useSite));
|
||||
}
|
||||
|
||||
export function typeOnlyDeclarationIsExport(typeOnlyDeclaration: Node) {
|
||||
return typeOnlyDeclaration.kind === SyntaxKind.ExportSpecifier;
|
||||
}
|
||||
|
||||
function isShorthandPropertyNameUseSite(useSite: Node) {
|
||||
return isIdentifier(useSite) && isShorthandPropertyAssignment(useSite.parent) && useSite.parent.name === useSite;
|
||||
}
|
||||
@@ -7409,4 +7461,120 @@ namespace ts {
|
||||
export function isInfinityOrNaNString(name: string | __String): boolean {
|
||||
return name === "Infinity" || name === "-Infinity" || name === "NaN";
|
||||
}
|
||||
|
||||
export function isCatchClauseVariableDeclaration(node: Node) {
|
||||
return node.kind === SyntaxKind.VariableDeclaration && node.parent.kind === SyntaxKind.CatchClause;
|
||||
}
|
||||
|
||||
export function isParameterOrCatchClauseVariable(symbol: Symbol) {
|
||||
const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration);
|
||||
return !!declaration && (isParameter(declaration) || isCatchClauseVariableDeclaration(declaration));
|
||||
}
|
||||
|
||||
export function isFunctionExpressionOrArrowFunction(node: Node): node is FunctionExpression | ArrowFunction {
|
||||
return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction;
|
||||
}
|
||||
|
||||
export function escapeSnippetText(text: string): string {
|
||||
return text.replace(/\$/gm, () => "\\$");
|
||||
}
|
||||
|
||||
export function isNumericLiteralName(name: string | __String) {
|
||||
// The intent of numeric names is that
|
||||
// - they are names with text in a numeric form, and that
|
||||
// - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
|
||||
// acquired by applying the abstract 'ToNumber' operation on the name's text.
|
||||
//
|
||||
// The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
|
||||
// In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
|
||||
//
|
||||
// Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
|
||||
// according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
|
||||
// Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
|
||||
// because their 'ToString' representation is not equal to their original text.
|
||||
// This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
|
||||
//
|
||||
// Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
|
||||
// The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
|
||||
// Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
|
||||
//
|
||||
// Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
|
||||
// This is desired behavior, because when indexing with them as numeric entities, you are indexing
|
||||
// with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
|
||||
return (+name).toString() === name;
|
||||
}
|
||||
|
||||
export function createPropertyNameNodeForIdentifierOrLiteral(name: string, target: ScriptTarget, singleQuote?: boolean, stringNamed?: boolean) {
|
||||
return isIdentifierText(name, target) ? factory.createIdentifier(name) :
|
||||
!stringNamed && isNumericLiteralName(name) && +name >= 0 ? factory.createNumericLiteral(+name) :
|
||||
factory.createStringLiteral(name, !!singleQuote);
|
||||
}
|
||||
|
||||
export function isThisTypeParameter(type: Type): boolean {
|
||||
return !!(type.flags & TypeFlags.TypeParameter && (type as TypeParameter).isThisType);
|
||||
}
|
||||
|
||||
export interface NodeModulePathParts {
|
||||
readonly topLevelNodeModulesIndex: number;
|
||||
readonly topLevelPackageNameIndex: number;
|
||||
readonly packageRootIndex: number;
|
||||
readonly fileNameIndex: number;
|
||||
}
|
||||
export function getNodeModulePathParts(fullPath: string): NodeModulePathParts | undefined {
|
||||
// If fullPath can't be valid module file within node_modules, returns undefined.
|
||||
// Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
|
||||
// Returns indices: ^ ^ ^ ^
|
||||
|
||||
let topLevelNodeModulesIndex = 0;
|
||||
let topLevelPackageNameIndex = 0;
|
||||
let packageRootIndex = 0;
|
||||
let fileNameIndex = 0;
|
||||
|
||||
const enum States {
|
||||
BeforeNodeModules,
|
||||
NodeModules,
|
||||
Scope,
|
||||
PackageContent
|
||||
}
|
||||
|
||||
let partStart = 0;
|
||||
let partEnd = 0;
|
||||
let state = States.BeforeNodeModules;
|
||||
|
||||
while (partEnd >= 0) {
|
||||
partStart = partEnd;
|
||||
partEnd = fullPath.indexOf("/", partStart + 1);
|
||||
switch (state) {
|
||||
case States.BeforeNodeModules:
|
||||
if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
|
||||
topLevelNodeModulesIndex = partStart;
|
||||
topLevelPackageNameIndex = partEnd;
|
||||
state = States.NodeModules;
|
||||
}
|
||||
break;
|
||||
case States.NodeModules:
|
||||
case States.Scope:
|
||||
if (state === States.NodeModules && fullPath.charAt(partStart + 1) === "@") {
|
||||
state = States.Scope;
|
||||
}
|
||||
else {
|
||||
packageRootIndex = partEnd;
|
||||
state = States.PackageContent;
|
||||
}
|
||||
break;
|
||||
case States.PackageContent:
|
||||
if (fullPath.indexOf(nodeModulesPathPart, partStart) === partStart) {
|
||||
state = States.NodeModules;
|
||||
}
|
||||
else {
|
||||
state = States.PackageContent;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
fileNameIndex = partStart;
|
||||
|
||||
return state > States.NodeModules ? { topLevelNodeModulesIndex, topLevelPackageNameIndex, packageRootIndex, fileNameIndex } : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,9 +11,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function getDefaultLibFileName(options: CompilerOptions): string {
|
||||
switch (options.target) {
|
||||
switch (getEmitScriptTarget(options)) {
|
||||
case ScriptTarget.ESNext:
|
||||
return "lib.esnext.full.d.ts";
|
||||
case ScriptTarget.ES2022:
|
||||
return "lib.es2022.full.d.ts";
|
||||
case ScriptTarget.ES2021:
|
||||
return "lib.es2021.full.d.ts";
|
||||
case ScriptTarget.ES2020:
|
||||
@@ -903,9 +905,16 @@ namespace ts {
|
||||
/** Gets the text of a jsdoc comment, flattening links to their text. */
|
||||
export function getTextOfJSDocComment(comment?: string | NodeArray<JSDocComment>) {
|
||||
return typeof comment === "string" ? comment
|
||||
: comment?.map(c =>
|
||||
// TODO: Other kinds here
|
||||
c.kind === SyntaxKind.JSDocText ? c.text : `{@link ${c.name ? entityNameToString(c.name) + " " : ""}${c.text}}`).join("");
|
||||
: comment?.map(c => c.kind === SyntaxKind.JSDocText ? c.text : formatJSDocLink(c)).join("");
|
||||
}
|
||||
|
||||
function formatJSDocLink(link: JSDocLink | JSDocLinkCode | JSDocLinkPlain) {
|
||||
const kind = link.kind === SyntaxKind.JSDocLink ? "link"
|
||||
: link.kind === SyntaxKind.JSDocLinkCode ? "linkcode"
|
||||
: "linkplain";
|
||||
const name = link.name ? entityNameToString(link.name) : "";
|
||||
const space = link.name && link.text.startsWith("://") ? "" : " ";
|
||||
return `{@${kind} ${name}${space}${link.text}}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1130,7 +1139,7 @@ namespace ts {
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
case SyntaxKind.ExportSpecifier:
|
||||
return (node as ImportOrExportSpecifier).parent.parent.isTypeOnly;
|
||||
return (node as ImportOrExportSpecifier).isTypeOnly || (node as ImportOrExportSpecifier).parent.parent.isTypeOnly;
|
||||
case SyntaxKind.NamespaceImport:
|
||||
return (node as NamespaceImport).parent.isTypeOnly;
|
||||
case SyntaxKind.ImportClause:
|
||||
@@ -1141,6 +1150,10 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
export function isAssertionKey(node: Node): node is AssertionKey {
|
||||
return isStringLiteral(node) || isIdentifier(node);
|
||||
}
|
||||
|
||||
export function isStringTextContainingNode(node: Node): node is StringLiteral | TemplateLiteralToken {
|
||||
return node.kind === SyntaxKind.StringLiteral || isTemplateLiteralKind(node.kind);
|
||||
}
|
||||
@@ -1512,6 +1525,7 @@ namespace ts {
|
||||
case SyntaxKind.ClassExpression:
|
||||
case SyntaxKind.FunctionExpression:
|
||||
case SyntaxKind.Identifier:
|
||||
case SyntaxKind.PrivateIdentifier: // technically this is only an Expression if it's in a `#field in expr` BinaryExpression
|
||||
case SyntaxKind.RegularExpressionLiteral:
|
||||
case SyntaxKind.NumericLiteral:
|
||||
case SyntaxKind.BigIntLiteral:
|
||||
@@ -1524,6 +1538,7 @@ namespace ts {
|
||||
case SyntaxKind.TrueKeyword:
|
||||
case SyntaxKind.SuperKeyword:
|
||||
case SyntaxKind.NonNullExpression:
|
||||
case SyntaxKind.ExpressionWithTypeArguments:
|
||||
case SyntaxKind.MetaProperty:
|
||||
case SyntaxKind.ImportKeyword: // technically this is only an Expression if it's in a CallExpression
|
||||
return true;
|
||||
|
||||
@@ -538,7 +538,8 @@ namespace ts {
|
||||
case SyntaxKind.TypeQuery:
|
||||
Debug.type<TypeQueryNode>(node);
|
||||
return factory.updateTypeQueryNode(node,
|
||||
nodeVisitor(node.exprName, visitor, isEntityName));
|
||||
nodeVisitor(node.exprName, visitor, isEntityName),
|
||||
nodesVisitor(node.typeArguments, visitor, isTypeNode));
|
||||
|
||||
case SyntaxKind.TypeLiteral:
|
||||
Debug.type<TypeLiteralNode>(node);
|
||||
@@ -629,7 +630,8 @@ namespace ts {
|
||||
nodeVisitor(node.typeParameter, visitor, isTypeParameterDeclaration),
|
||||
nodeVisitor(node.nameType, visitor, isTypeNode),
|
||||
nodeVisitor(node.questionToken, tokenVisitor, isQuestionOrPlusOrMinusToken),
|
||||
nodeVisitor(node.type, visitor, isTypeNode));
|
||||
nodeVisitor(node.type, visitor, isTypeNode),
|
||||
nodesVisitor(node.members, visitor, isTypeElement));
|
||||
|
||||
case SyntaxKind.LiteralType:
|
||||
Debug.type<LiteralTypeNode>(node);
|
||||
@@ -1076,7 +1078,20 @@ namespace ts {
|
||||
nodesVisitor(node.decorators, visitor, isDecorator),
|
||||
nodesVisitor(node.modifiers, visitor, isModifier),
|
||||
nodeVisitor(node.importClause, visitor, isImportClause),
|
||||
nodeVisitor(node.moduleSpecifier, visitor, isExpression));
|
||||
nodeVisitor(node.moduleSpecifier, visitor, isExpression),
|
||||
nodeVisitor(node.assertClause, visitor, isAssertClause));
|
||||
|
||||
case SyntaxKind.AssertClause:
|
||||
Debug.type<AssertClause>(node);
|
||||
return factory.updateAssertClause(node,
|
||||
nodesVisitor(node.elements, visitor, isAssertEntry),
|
||||
node.multiLine);
|
||||
|
||||
case SyntaxKind.AssertEntry:
|
||||
Debug.type<AssertEntry>(node);
|
||||
return factory.updateAssertEntry(node,
|
||||
nodeVisitor(node.name, visitor, isAssertionKey),
|
||||
nodeVisitor(node.value, visitor, isExpressionNode));
|
||||
|
||||
case SyntaxKind.ImportClause:
|
||||
Debug.type<ImportClause>(node);
|
||||
@@ -1103,6 +1118,7 @@ namespace ts {
|
||||
case SyntaxKind.ImportSpecifier:
|
||||
Debug.type<ImportSpecifier>(node);
|
||||
return factory.updateImportSpecifier(node,
|
||||
node.isTypeOnly,
|
||||
nodeVisitor(node.propertyName, visitor, isIdentifier),
|
||||
nodeVisitor(node.name, visitor, isIdentifier));
|
||||
|
||||
@@ -1120,7 +1136,8 @@ namespace ts {
|
||||
nodesVisitor(node.modifiers, visitor, isModifier),
|
||||
node.isTypeOnly,
|
||||
nodeVisitor(node.exportClause, visitor, isNamedExportBindings),
|
||||
nodeVisitor(node.moduleSpecifier, visitor, isExpression));
|
||||
nodeVisitor(node.moduleSpecifier, visitor, isExpression),
|
||||
nodeVisitor(node.assertClause, visitor, isAssertClause));
|
||||
|
||||
case SyntaxKind.NamedExports:
|
||||
Debug.type<NamedExports>(node);
|
||||
@@ -1130,6 +1147,7 @@ namespace ts {
|
||||
case SyntaxKind.ExportSpecifier:
|
||||
Debug.type<ExportSpecifier>(node);
|
||||
return factory.updateExportSpecifier(node,
|
||||
node.isTypeOnly,
|
||||
nodeVisitor(node.propertyName, visitor, isIdentifier),
|
||||
nodeVisitor(node.name, visitor, isIdentifier));
|
||||
|
||||
|
||||
+96
-8
@@ -7,7 +7,7 @@ namespace ts {
|
||||
} : undefined;
|
||||
|
||||
/**
|
||||
* Create a function that reports error by writing to the system and handles the formating of the diagnostic
|
||||
* Create a function that reports error by writing to the system and handles the formatting of the diagnostic
|
||||
*/
|
||||
export function createDiagnosticReporter(system: System, pretty?: boolean): DiagnosticReporter {
|
||||
const host: FormatDiagnosticsHost = system === sys && sysFormatDiagnosticsHost ? sysFormatDiagnosticsHost : {
|
||||
@@ -64,7 +64,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
|
||||
* Create a function that reports watch status by writing to the system and handles the formatting of the diagnostic
|
||||
*/
|
||||
export function createWatchStatusReporter(system: System, pretty?: boolean): WatchStatusReporter {
|
||||
return pretty ?
|
||||
@@ -101,16 +101,104 @@ namespace ts {
|
||||
return countWhere(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error);
|
||||
}
|
||||
|
||||
export function getFilesInErrorForSummary(diagnostics: readonly Diagnostic[]): (ReportFileInError | undefined)[] {
|
||||
const filesInError =
|
||||
filter(diagnostics, diagnostic => diagnostic.category === DiagnosticCategory.Error)
|
||||
.map(
|
||||
errorDiagnostic => {
|
||||
if(errorDiagnostic.file === undefined) return;
|
||||
return `${errorDiagnostic.file.fileName}`;
|
||||
});
|
||||
return filesInError.map((fileName: string) => {
|
||||
const diagnosticForFileName = find(diagnostics, diagnostic =>
|
||||
diagnostic.file !== undefined && diagnostic.file.fileName === fileName
|
||||
);
|
||||
|
||||
if(diagnosticForFileName !== undefined) {
|
||||
const { line } = getLineAndCharacterOfPosition(diagnosticForFileName.file!, diagnosticForFileName.start!);
|
||||
return {
|
||||
fileName,
|
||||
line: line + 1,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function getWatchErrorSummaryDiagnosticMessage(errorCount: number) {
|
||||
return errorCount === 1 ?
|
||||
Diagnostics.Found_1_error_Watching_for_file_changes :
|
||||
Diagnostics.Found_0_errors_Watching_for_file_changes;
|
||||
}
|
||||
|
||||
export function getErrorSummaryText(errorCount: number, newLine: string) {
|
||||
function prettyPathForFileError(error: ReportFileInError, cwd: string) {
|
||||
const line = formatColorAndReset(":" + error.line, ForegroundColorEscapeSequences.Grey);
|
||||
if (pathIsAbsolute(error.fileName) && pathIsAbsolute(cwd)) {
|
||||
return getRelativePathFromDirectory(cwd, error.fileName, /* ignoreCase */ false) + line;
|
||||
}
|
||||
|
||||
return error.fileName + line;
|
||||
}
|
||||
|
||||
export function getErrorSummaryText(
|
||||
errorCount: number,
|
||||
filesInError: readonly (ReportFileInError | undefined)[],
|
||||
newLine: string,
|
||||
host: HasCurrentDirectory
|
||||
) {
|
||||
if (errorCount === 0) return "";
|
||||
const d = createCompilerDiagnostic(errorCount === 1 ? Diagnostics.Found_1_error : Diagnostics.Found_0_errors, errorCount);
|
||||
return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}`;
|
||||
const nonNilFiles = filesInError.filter(fileInError => fileInError !== undefined);
|
||||
const distinctFileNamesWithLines = nonNilFiles.map(fileInError => `${fileInError!.fileName}:${fileInError!.line}`)
|
||||
.filter((value, index, self) => self.indexOf(value) === index);
|
||||
|
||||
const firstFileReference = nonNilFiles[0] && prettyPathForFileError(nonNilFiles[0], host.getCurrentDirectory());
|
||||
|
||||
const d = errorCount === 1 ?
|
||||
createCompilerDiagnostic(
|
||||
filesInError[0] !== undefined ?
|
||||
Diagnostics.Found_1_error_in_1 :
|
||||
Diagnostics.Found_1_error,
|
||||
errorCount,
|
||||
firstFileReference) :
|
||||
createCompilerDiagnostic(
|
||||
distinctFileNamesWithLines.length === 0 ?
|
||||
Diagnostics.Found_0_errors :
|
||||
distinctFileNamesWithLines.length === 1 ?
|
||||
Diagnostics.Found_0_errors_in_the_same_file_starting_at_Colon_1 :
|
||||
Diagnostics.Found_0_errors_in_1_files,
|
||||
errorCount,
|
||||
distinctFileNamesWithLines.length === 1 ? firstFileReference : distinctFileNamesWithLines.length);
|
||||
|
||||
const suffix = distinctFileNamesWithLines.length > 1 ? createTabularErrorsDisplay(nonNilFiles, host) : "";
|
||||
return `${newLine}${flattenDiagnosticMessageText(d.messageText, newLine)}${newLine}${newLine}${suffix}`;
|
||||
}
|
||||
|
||||
function createTabularErrorsDisplay(filesInError: (ReportFileInError | undefined)[], host: HasCurrentDirectory) {
|
||||
const distinctFiles = filesInError.filter((value, index, self) => index === self.findIndex(file => file?.fileName === value?.fileName));
|
||||
if (distinctFiles.length === 0) return "";
|
||||
|
||||
const numberLength = (num: number) => Math.log(num) * Math.LOG10E + 1;
|
||||
const fileToErrorCount = distinctFiles.map(file => ([file, countWhere(filesInError, fileInError => fileInError!.fileName === file!.fileName)] as const));
|
||||
const maxErrors = fileToErrorCount.reduce((acc, value) => Math.max(acc, value[1] || 0), 0);
|
||||
|
||||
const headerRow = Diagnostics.Errors_Files.message;
|
||||
const leftColumnHeadingLength = headerRow.split(" ")[0].length;
|
||||
const leftPaddingGoal = Math.max(leftColumnHeadingLength, numberLength(maxErrors));
|
||||
const headerPadding = Math.max(numberLength(maxErrors) - leftColumnHeadingLength, 0);
|
||||
|
||||
let tabularData = "";
|
||||
tabularData += " ".repeat(headerPadding) + headerRow + "\n";
|
||||
fileToErrorCount.forEach((row) => {
|
||||
const [file, errorCount] = row;
|
||||
const errorCountDigitsLength = Math.log(errorCount) * Math.LOG10E + 1 | 0;
|
||||
const leftPadding = errorCountDigitsLength < leftPaddingGoal ?
|
||||
" ".repeat(leftPaddingGoal - errorCountDigitsLength)
|
||||
: "";
|
||||
|
||||
const fileRef = prettyPathForFileError(file!, host.getCurrentDirectory());
|
||||
tabularData += `${leftPadding}${errorCount} ${fileRef}\n`;
|
||||
});
|
||||
|
||||
return tabularData;
|
||||
}
|
||||
|
||||
export function isBuilderProgram(program: Program | BuilderProgram): program is BuilderProgram {
|
||||
@@ -279,7 +367,7 @@ namespace ts {
|
||||
);
|
||||
case FileIncludeKind.LibFile:
|
||||
if (reason.index !== undefined) return chainDiagnosticMessages(/*details*/ undefined, Diagnostics.Library_0_specified_in_compilerOptions, options.lib![reason.index]);
|
||||
const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === options.target ? key : undefined);
|
||||
const target = forEachEntry(targetOptionDeclaration.type, (value, key) => value === getEmitScriptTarget(options) ? key : undefined);
|
||||
return chainDiagnosticMessages(
|
||||
/*details*/ undefined,
|
||||
target ?
|
||||
@@ -350,7 +438,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
if (reportSummary) {
|
||||
reportSummary(getErrorCountForSummary(diagnostics));
|
||||
reportSummary(getErrorCountForSummary(diagnostics), getFilesInErrorForSummary(diagnostics));
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -656,7 +744,7 @@ namespace ts {
|
||||
builderProgram,
|
||||
input.reportDiagnostic || createDiagnosticReporter(system),
|
||||
s => host.trace && host.trace(s),
|
||||
input.reportErrorSummary || input.options.pretty ? errorCount => system.write(getErrorSummaryText(errorCount, system.newLine)) : undefined
|
||||
input.reportErrorSummary || input.options.pretty ? (errorCount, filesInError) => system.write(getErrorSummaryText(errorCount, filesInError, system.newLine, host)) : undefined
|
||||
);
|
||||
if (input.afterProgramEmitAndDiagnostics) input.afterProgramEmitAndDiagnostics(builderProgram);
|
||||
return exitStatus;
|
||||
|
||||
@@ -101,9 +101,9 @@ namespace ts {
|
||||
getEnvironmentVariable?(name: string): string | undefined;
|
||||
|
||||
/** If provided, used to resolve the module names, otherwise typescript's default module resolution */
|
||||
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedModule | undefined)[];
|
||||
resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames: string[] | undefined, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingSourceFile?: SourceFile): (ResolvedModule | undefined)[];
|
||||
/** If provided, used to resolve type reference directives, otherwise typescript's default resolution */
|
||||
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[] | readonly FileReference[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions, containingFileMode?: SourceFile["impliedNodeFormat"] | undefined): (ResolvedTypeReferenceDirective | undefined)[];
|
||||
}
|
||||
/** Internal interface used to wire emit through same host */
|
||||
|
||||
@@ -273,6 +273,7 @@ namespace ts {
|
||||
let sharedExtendedConfigFileWatchers: ESMap<Path, SharedExtendedConfigFileWatcher<Path>>; // Map of file watchers for extended files, shared between different referenced projects
|
||||
let extendedConfigCache = host.extendedConfigCache; // Cache for extended config evaluation
|
||||
let changesAffectResolution = false; // Flag for indicating non-config changes affect module resolution
|
||||
let reportFileChangeDetectedOnCreateProgram = false; // True if synchronizeProgram should report "File change detected..." when a new program is created
|
||||
|
||||
const sourceFilesCache = new Map<string, HostFileInfo>(); // Cache that stores the source file and version info
|
||||
let missingFilePathsRequestedForRelease: Path[] | undefined; // These paths are held temporarily so that we can remove the entry from source file cache if the file is not tracked by missing files
|
||||
@@ -349,10 +350,10 @@ namespace ts {
|
||||
// Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
|
||||
compilerHost.resolveModuleNames = host.resolveModuleNames ?
|
||||
((...args) => host.resolveModuleNames!(...args)) :
|
||||
((moduleNames, containingFile, reusedNames, redirectedReference) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference));
|
||||
((moduleNames, containingFile, reusedNames, redirectedReference, _options, sourceFile) => resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference, sourceFile));
|
||||
compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
|
||||
((...args) => host.resolveTypeReferenceDirectives!(...args)) :
|
||||
((typeDirectiveNames, containingFile, redirectedReference) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference));
|
||||
((typeDirectiveNames, containingFile, redirectedReference, _options, containingFileMode) => resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference, containingFileMode));
|
||||
const userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
|
||||
|
||||
builderProgram = readBuilderProgram(compilerOptions, compilerHost) as any as T;
|
||||
@@ -434,15 +435,22 @@ namespace ts {
|
||||
const hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution || changesAffectResolution);
|
||||
if (isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, getParsedCommandLine, projectReferences)) {
|
||||
if (hasChangedConfigFileParsingErrors) {
|
||||
if (reportFileChangeDetectedOnCreateProgram) {
|
||||
reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation);
|
||||
}
|
||||
builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
|
||||
hasChangedConfigFileParsingErrors = false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (reportFileChangeDetectedOnCreateProgram) {
|
||||
reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation);
|
||||
}
|
||||
createNewProgram(hasInvalidatedResolution);
|
||||
}
|
||||
|
||||
changesAffectResolution = false; // reset for next sync
|
||||
reportFileChangeDetectedOnCreateProgram = false;
|
||||
|
||||
if (host.afterProgramCreate && program !== builderProgram) {
|
||||
host.afterProgramCreate(builderProgram);
|
||||
@@ -560,6 +568,9 @@ namespace ts {
|
||||
sourceFilesCache.set(path, false);
|
||||
}
|
||||
}
|
||||
if (sourceFile) {
|
||||
sourceFile.impliedNodeFormat = getImpliedNodeFormatForFile(path, resolutionCache.getModuleResolutionCache().getPackageJsonInfoCache(), compilerHost, compilerHost.getCompilationSettings());
|
||||
}
|
||||
return sourceFile;
|
||||
}
|
||||
return hostSourceFile.sourceFile;
|
||||
@@ -662,7 +673,7 @@ namespace ts {
|
||||
|
||||
function updateProgramWithWatchStatus() {
|
||||
timerToUpdateProgram = undefined;
|
||||
reportWatchDiagnostic(Diagnostics.File_change_detected_Starting_incremental_compilation);
|
||||
reportFileChangeDetectedOnCreateProgram = true;
|
||||
updateProgram();
|
||||
}
|
||||
|
||||
|
||||
@@ -184,7 +184,7 @@ namespace ts {
|
||||
const rootResult = tryReadDirectory(rootDir, rootDirPath);
|
||||
let rootSymLinkResult: FileSystemEntries | 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);
|
||||
|
||||
@@ -499,7 +499,7 @@ namespace ts {
|
||||
// If its declaration directory: its not ignored if not excluded by config
|
||||
if (options.declarationDir) return false;
|
||||
}
|
||||
else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensions)) {
|
||||
else if (!fileExtensionIsOneOf(fileOrDirectoryPath, supportedJSExtensionsFlat)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -1224,7 +1224,7 @@ namespace ts {
|
||||
exportClause: NamedExportBindings | undefined,
|
||||
moduleSpecifier: Expression | undefined,
|
||||
isTypeOnly: boolean) {
|
||||
return factory.updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier);
|
||||
return factory.updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier, node.assertClause);
|
||||
}, factoryDeprecation);
|
||||
|
||||
/** @deprecated Use `factory.createJSDocParameterTag` or the factory supplied by your transformation context instead. */
|
||||
|
||||
@@ -43,10 +43,10 @@ namespace ts {
|
||||
}
|
||||
|
||||
const path = file.path;
|
||||
if (fileExtensionIsOneOf(path, supportedTSExtensions)) {
|
||||
if (fileExtensionIsOneOf(path, supportedTSExtensionsFlat)) {
|
||||
return "TypeScript";
|
||||
}
|
||||
else if (fileExtensionIsOneOf(path, supportedJSExtensions)) {
|
||||
else if (fileExtensionIsOneOf(path, supportedJSExtensionsFlat)) {
|
||||
return "JavaScript";
|
||||
}
|
||||
else if (fileExtensionIs(path, Extension.Json)) {
|
||||
@@ -160,7 +160,13 @@ namespace ts {
|
||||
|
||||
// value type and possible value
|
||||
const valueCandidates = getValueCandidate(option);
|
||||
const defaultValueDescription = typeof option.defaultValueDescription === "object" ? getDiagnosticText(option.defaultValueDescription) : option.defaultValueDescription;
|
||||
const defaultValueDescription =
|
||||
typeof option.defaultValueDescription === "object"
|
||||
? getDiagnosticText(option.defaultValueDescription)
|
||||
: formatDefaultValue(
|
||||
option.defaultValueDescription,
|
||||
option.type === "list" ? option.element.type : option.type
|
||||
);
|
||||
const terminalWidth = sys.getWidthOfTerminal?.() ?? 0;
|
||||
|
||||
// Note: child_process might return `terminalWidth` as undefined.
|
||||
@@ -203,6 +209,19 @@ namespace ts {
|
||||
}
|
||||
return text;
|
||||
|
||||
function formatDefaultValue(
|
||||
defaultValue: CommandLineOption["defaultValueDescription"],
|
||||
type: CommandLineOption["type"]
|
||||
) {
|
||||
return defaultValue !== undefined && typeof type === "object"
|
||||
// e.g. ScriptTarget.ES2015 -> "es6/es2015"
|
||||
? arrayFrom(type.entries())
|
||||
.filter(([, value]) => value === defaultValue)
|
||||
.map(([name]) => name)
|
||||
.join("/")
|
||||
: String(defaultValue);
|
||||
}
|
||||
|
||||
function showAdditionalInfoOutput(valueCandidates: ValueCandidate | undefined, option: CommandLineOption): boolean {
|
||||
const ignoreValues = ["string"];
|
||||
const ignoredDescriptions = [undefined, "false", "n/a"];
|
||||
@@ -286,8 +305,14 @@ namespace ts {
|
||||
break;
|
||||
default:
|
||||
// ESMap<string, number | string>
|
||||
const keys = arrayFrom(option.type.keys());
|
||||
possibleValues = keys.join(", ");
|
||||
// Group synonyms: es6/es2015
|
||||
const inverted: { [value: string]: string[] } = {};
|
||||
option.type.forEach((value, name) => {
|
||||
(inverted[value] ||= []).push(name);
|
||||
});
|
||||
return getEntries(inverted)
|
||||
.map(([, synonyms]) => synonyms.join("/"))
|
||||
.join(", ");
|
||||
}
|
||||
return possibleValues;
|
||||
}
|
||||
@@ -354,7 +379,7 @@ namespace ts {
|
||||
|
||||
function printEasyHelp(sys: System, simpleOptions: readonly CommandLineOption[]) {
|
||||
const colors = createColors(sys);
|
||||
let output: string[] = [...getHelpHeader(sys)];
|
||||
let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)];
|
||||
output.push(colors.bold(getDiagnosticText(Diagnostics.COMMON_COMMANDS)) + sys.newLine + sys.newLine);
|
||||
|
||||
example("tsc", Diagnostics.Compiles_the_current_project_tsconfig_json_in_the_working_directory);
|
||||
@@ -388,7 +413,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
function printAllHelp(sys: System, compilerOptions: readonly CommandLineOption[], buildOptions: readonly CommandLineOption[], watchOptions: readonly CommandLineOption[]) {
|
||||
let output: string[] = [...getHelpHeader(sys)];
|
||||
let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)];
|
||||
output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.ALL_COMPILER_OPTIONS), compilerOptions, /*subCategory*/ true, /* beforeOptionsDescription */ undefined, formatMessage(/*_dummy*/ undefined, Diagnostics.You_can_learn_about_all_of_the_compiler_options_at_0, "https://aka.ms/tsconfig-reference"))];
|
||||
output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.WATCH_OPTIONS), watchOptions, /*subCategory*/ false, getDiagnosticText(Diagnostics.Including_watch_w_will_start_watching_the_current_project_for_the_file_changes_Once_set_you_can_config_watch_mode_with_Colon))];
|
||||
output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(/*_dummy*/ undefined, Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))];
|
||||
@@ -398,32 +423,31 @@ namespace ts {
|
||||
}
|
||||
|
||||
function printBuildHelp(sys: System, buildOptions: readonly CommandLineOption[]) {
|
||||
let output: string[] = [...getHelpHeader(sys)];
|
||||
let output: string[] = [...getHeader(sys,`${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`)];
|
||||
output = [...output, ...generateSectionOptionsOutput(sys, getDiagnosticText(Diagnostics.BUILD_OPTIONS), buildOptions, /*subCategory*/ false, formatMessage(/*_dummy*/ undefined, Diagnostics.Using_build_b_will_make_tsc_behave_more_like_a_build_orchestrator_than_a_compiler_This_is_used_to_trigger_building_composite_projects_which_you_can_learn_more_about_at_0, "https://aka.ms/tsc-composite-builds"))];
|
||||
for (const line of output) {
|
||||
sys.write(line);
|
||||
}
|
||||
}
|
||||
|
||||
function getHelpHeader(sys: System) {
|
||||
function getHeader(sys: System, message: string) {
|
||||
const colors = createColors(sys);
|
||||
const header: string[] = [];
|
||||
const tscExplanation = `${getDiagnosticText(Diagnostics.tsc_Colon_The_TypeScript_Compiler)} - ${getDiagnosticText(Diagnostics.Version_0, version)}`;
|
||||
const terminalWidth = sys.getWidthOfTerminal?.() ?? 0;;
|
||||
const tsIconLength = 5;
|
||||
|
||||
const tsIconFirstLine = colors.blueBackground(padLeft("", tsIconLength));
|
||||
const tsIconSecondLine = colors.blueBackground(colors.brightWhite(padLeft("TS ", tsIconLength)));
|
||||
// If we have enough space, print TS icon.
|
||||
if (terminalWidth >= tscExplanation.length + tsIconLength) {
|
||||
if (terminalWidth >= message.length + tsIconLength) {
|
||||
// right align of the icon is 120 at most.
|
||||
const rightAlign = terminalWidth > 120 ? 120 : terminalWidth;
|
||||
const leftAlign = rightAlign - tsIconLength;
|
||||
header.push(padRight(tscExplanation, leftAlign) + tsIconFirstLine + sys.newLine);
|
||||
header.push(padRight(message, leftAlign) + tsIconFirstLine + sys.newLine);
|
||||
header.push(padLeft("", leftAlign) + tsIconSecondLine + sys.newLine);
|
||||
}
|
||||
else {
|
||||
header.push(tscExplanation + sys.newLine);
|
||||
header.push(message + sys.newLine);
|
||||
header.push(sys.newLine);
|
||||
}
|
||||
return header;
|
||||
@@ -749,7 +773,7 @@ namespace ts {
|
||||
|
||||
function createReportErrorSummary(sys: System, options: CompilerOptions | BuildOptions): ReportEmitErrorSummary | undefined {
|
||||
return shouldBePretty(sys, options) ?
|
||||
errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) :
|
||||
(errorCount, filesInError) => sys.write(getErrorSummaryText(errorCount, filesInError, sys.newLine, sys)) :
|
||||
undefined;
|
||||
}
|
||||
|
||||
@@ -1035,7 +1059,12 @@ namespace ts {
|
||||
}
|
||||
else {
|
||||
sys.writeFile(file, generateTSConfig(options, fileNames, sys.newLine));
|
||||
reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file));
|
||||
const output: string[] = [sys.newLine, ...getHeader(sys,"Created a new tsconfig.json with:")];
|
||||
output.push(getCompilerOptionsDiffValue(options, sys.newLine) + sys.newLine + sys.newLine);
|
||||
output.push(`You can learn more at https://aka.ms/tsconfig.json` + sys.newLine);
|
||||
for (const line of output) {
|
||||
sys.write(line);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
|
||||
@@ -118,11 +118,11 @@ namespace compiler {
|
||||
const input = new documents.TextDocument(sourceFile.fileName, sourceFile.text);
|
||||
this._inputs.push(input);
|
||||
if (!vpath.isDeclaration(sourceFile.fileName)) {
|
||||
const extname = ts.getOutputExtension(sourceFile, this.options);
|
||||
const extname = ts.getOutputExtension(sourceFile.fileName, this.options);
|
||||
const outputs: CompilationOutput = {
|
||||
inputs: [input],
|
||||
js: js.get(this.getOutputPath(sourceFile.fileName, extname)),
|
||||
dts: dts.get(this.getOutputPath(sourceFile.fileName, ".d.ts")),
|
||||
dts: dts.get(this.getOutputPath(sourceFile.fileName, ts.getDeclarationEmitExtensionForPath(sourceFile.fileName))),
|
||||
map: maps.get(this.getOutputPath(sourceFile.fileName, extname + ".map"))
|
||||
};
|
||||
|
||||
@@ -205,7 +205,7 @@ namespace compiler {
|
||||
}
|
||||
else {
|
||||
path = vpath.resolve(this.vfs.cwd(), path);
|
||||
const outDir = ext === ".d.ts" ? this.options.declarationDir || this.options.outDir : this.options.outDir;
|
||||
const outDir = ext === ".d.ts" || ext === ".json.d.ts" || ext === ".d.mts" || ext === ".d.cts" ? this.options.declarationDir || this.options.outDir : this.options.outDir;
|
||||
if (outDir) {
|
||||
const common = this.commonSourceDirectory;
|
||||
if (common) {
|
||||
@@ -249,7 +249,7 @@ namespace compiler {
|
||||
}
|
||||
|
||||
// establish defaults (aligns with old harness)
|
||||
if (compilerOptions.target === undefined) compilerOptions.target = ts.ScriptTarget.ES3;
|
||||
if (compilerOptions.target === undefined && compilerOptions.module !== ts.ModuleKind.Node12 && compilerOptions.module !== ts.ModuleKind.NodeNext) compilerOptions.target = ts.ScriptTarget.ES3;
|
||||
if (compilerOptions.newLine === undefined) compilerOptions.newLine = ts.NewLineKind.CarriageReturnLineFeed;
|
||||
if (compilerOptions.skipDefaultLibCheck === undefined) compilerOptions.skipDefaultLibCheck = true;
|
||||
if (compilerOptions.noErrorTruncation === undefined) compilerOptions.noErrorTruncation = true;
|
||||
@@ -264,7 +264,9 @@ namespace compiler {
|
||||
const program = ts.createProgram(rootFiles || [], compilerOptions, host);
|
||||
const emitResult = program.emit();
|
||||
const postErrors = ts.getPreEmitDiagnostics(program);
|
||||
const errors = preErrors && (preErrors.length !== postErrors.length) ? [...postErrors,
|
||||
const longerErrors = ts.length(preErrors) > postErrors.length ? preErrors : postErrors;
|
||||
const shorterErrors = longerErrors === preErrors ? postErrors : preErrors;
|
||||
const errors = preErrors && (preErrors.length !== postErrors.length) ? [...shorterErrors!,
|
||||
ts.addRelatedInfo(
|
||||
ts.createCompilerDiagnostic({
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
@@ -278,7 +280,7 @@ namespace compiler {
|
||||
key: "-1",
|
||||
message: `The excess diagnostics are:`
|
||||
}),
|
||||
...ts.filter(postErrors, p => !ts.some(preErrors, p2 => ts.compareDiagnostics(p, p2) === ts.Comparison.EqualTo))
|
||||
...ts.filter(longerErrors!, p => !ts.some(shorterErrors, p2 => ts.compareDiagnostics(p, p2) === ts.Comparison.EqualTo))
|
||||
)
|
||||
] : postErrors;
|
||||
return new CompilationResult(host, compilerOptions, program, emitResult, errors);
|
||||
|
||||
@@ -95,7 +95,7 @@ namespace fakes {
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace Utils {
|
||||
const { join, resolve, dirname } = require("path") as typeof import("path");
|
||||
const { existsSync } = require("fs") as typeof import("fs");
|
||||
|
||||
// search directories upward to avoid hard-wired paths based on the
|
||||
// build tree (same as scripts/build/findUpDir.js)
|
||||
|
||||
export function findUpFile(name: string): string {
|
||||
let dir = __dirname;
|
||||
while (true) {
|
||||
const fullPath = join(dir, name);
|
||||
if (existsSync(fullPath)) return fullPath;
|
||||
const up = resolve(dir, "..");
|
||||
if (up === dir) return name; // it'll fail anyway
|
||||
dir = up;
|
||||
}
|
||||
}
|
||||
|
||||
export const findUpRoot: { (): string; cached?: string; } = () =>
|
||||
findUpRoot.cached ||= dirname(findUpFile("Gulpfile.js"));
|
||||
}
|
||||
@@ -313,12 +313,13 @@ namespace FourSlash {
|
||||
this.addMatchedInputFile(referenceFilePath, /* extensions */ undefined);
|
||||
});
|
||||
|
||||
const exts = ts.flatten(ts.getSupportedExtensions(compilationOptions));
|
||||
// Add import files into language-service host
|
||||
ts.forEach(importedFiles, importedFile => {
|
||||
// Fourslash insert tests/cases/fourslash into inputFile.unitName and import statement doesn't require ".ts"
|
||||
// so convert them before making appropriate comparison
|
||||
const importedFilePath = this.basePath + "/" + importedFile.fileName;
|
||||
this.addMatchedInputFile(importedFilePath, ts.getSupportedExtensions(compilationOptions));
|
||||
this.addMatchedInputFile(importedFilePath, exts);
|
||||
});
|
||||
|
||||
// Check if no-default-lib flag is false and if so add default library
|
||||
@@ -636,7 +637,9 @@ namespace FourSlash {
|
||||
ts.forEachKey(this.inputFiles, fileName => {
|
||||
if (!ts.isAnySupportedFileExtension(fileName)
|
||||
|| Harness.getConfigNameFromFileName(fileName)
|
||||
|| !ts.getAllowJSCompilerOption(this.getProgram().getCompilerOptions()) && !ts.resolutionExtensionIsTSOrJson(ts.extensionFromPath(fileName))) return;
|
||||
// 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;
|
||||
const errors = this.getDiagnostics(fileName).filter(e => e.category !== ts.DiagnosticCategory.Suggestion);
|
||||
if (errors.length) {
|
||||
this.printErrorLog(/*expectErrors*/ false, errors);
|
||||
@@ -838,7 +841,7 @@ namespace FourSlash {
|
||||
});
|
||||
}
|
||||
|
||||
public verifyInlayHints(expected: readonly FourSlashInterface.VerifyInlayHintsOptions[], span: ts.TextSpan = { start: 0, length: this.activeFile.content.length }, preference?: ts.InlayHintsOptions) {
|
||||
public verifyInlayHints(expected: readonly FourSlashInterface.VerifyInlayHintsOptions[], span: ts.TextSpan = { start: 0, length: this.activeFile.content.length }, preference?: ts.UserPreferences) {
|
||||
const hints = this.languageService.provideInlayHints(this.activeFile.fileName, span, preference);
|
||||
assert.equal(hints.length, expected.length, "Number of hints");
|
||||
|
||||
@@ -911,9 +914,26 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
if (ts.hasProperty(options, "exact")) {
|
||||
ts.Debug.assert(!ts.hasProperty(options, "includes") && !ts.hasProperty(options, "excludes"));
|
||||
ts.Debug.assert(!ts.hasProperty(options, "includes") && !ts.hasProperty(options, "excludes") && !ts.hasProperty(options, "unsorted"));
|
||||
if (options.exact === undefined) throw this.raiseError("Expected no completions");
|
||||
this.verifyCompletionsAreExactly(actualCompletions.entries, toArray(options.exact), options.marker);
|
||||
this.verifyCompletionsAreExactly(actualCompletions.entries, options.exact, options.marker);
|
||||
}
|
||||
else if (options.unsorted) {
|
||||
ts.Debug.assert(!ts.hasProperty(options, "includes") && !ts.hasProperty(options, "excludes"));
|
||||
for (const expectedEntry of options.unsorted) {
|
||||
const name = typeof expectedEntry === "string" ? expectedEntry : expectedEntry.name;
|
||||
const found = nameToEntries.get(name);
|
||||
if (!found) throw this.raiseError(`Unsorted: completion '${name}' not found.`);
|
||||
if (!found.length) throw this.raiseError(`Unsorted: no completions with name '${name}' remain unmatched.`);
|
||||
this.verifyCompletionEntry(found.shift()!, expectedEntry);
|
||||
}
|
||||
if (actualCompletions.entries.length !== options.unsorted.length) {
|
||||
const unmatched: string[] = [];
|
||||
nameToEntries.forEach(entries => {
|
||||
unmatched.push(...entries.map(e => e.name));
|
||||
});
|
||||
this.raiseError(`Additional completions found not included in 'unsorted': ${unmatched.join("\n")}`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (options.includes) {
|
||||
@@ -940,7 +960,7 @@ namespace FourSlash {
|
||||
expected = typeof expected === "string" ? { name: expected } : expected;
|
||||
|
||||
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);
|
||||
if (convertedReplacementSpan?.length) {
|
||||
@@ -990,7 +1010,11 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
private verifyCompletionsAreExactly(actual: readonly ts.CompletionEntry[], expected: readonly FourSlashInterface.ExpectedCompletionEntry[], marker?: ArrayOrSingle<string | Marker>) {
|
||||
private verifyCompletionsAreExactly(actual: readonly ts.CompletionEntry[], expected: ArrayOrSingle<FourSlashInterface.ExpectedCompletionEntry> | FourSlashInterface.ExpectedExactCompletionsPlus, marker?: ArrayOrSingle<string | Marker>) {
|
||||
if (!ts.isArray(expected)) {
|
||||
expected = [expected];
|
||||
}
|
||||
|
||||
// First pass: test that names are right. Then we'll test details.
|
||||
assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name), marker ? "At marker " + JSON.stringify(marker) : undefined);
|
||||
|
||||
@@ -1001,6 +1025,16 @@ namespace FourSlash {
|
||||
}
|
||||
this.verifyCompletionEntry(completion, expectedCompletion);
|
||||
});
|
||||
|
||||
// All completions were correct in the sort order given. If that order was produced by a function
|
||||
// like `completion.globalsPlus`, ensure the "plus" array was sorted in the same way.
|
||||
const { plusArgument, plusFunctionName } = expected as FourSlashInterface.ExpectedExactCompletionsPlus;
|
||||
if (plusArgument) {
|
||||
assert.deepEqual(
|
||||
plusArgument,
|
||||
expected.filter(entry => plusArgument.includes(entry)),
|
||||
`At marker ${JSON.stringify(marker)}: Argument to '${plusFunctionName}' was incorrectly sorted.`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Use `getProgram` instead of accessing this directly. */
|
||||
@@ -1244,20 +1278,6 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
public verifyNoReferences(markerNameOrRange?: string | Range) {
|
||||
if (markerNameOrRange !== undefined) this.goToMarkerOrRange(markerNameOrRange);
|
||||
const refs = this.getReferencesAtCaret();
|
||||
if (refs && refs.length) {
|
||||
this.raiseError(`Expected getReferences to fail, but saw references: ${stringify(refs)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated - use `verify.baselineFindAllReferences()` instead. */
|
||||
public verifyGetReferencesForServerTest(expected: readonly ts.ReferenceEntry[]): void {
|
||||
const refs = this.getReferencesAtCaret();
|
||||
assert.deepEqual<readonly ts.ReferenceEntry[] | undefined>(refs, expected);
|
||||
}
|
||||
|
||||
public verifySingleReferenceGroup(definition: FourSlashInterface.ReferenceGroupDefinition, ranges?: Range[] | string) {
|
||||
ranges = ts.isString(ranges) ? this.rangesByText().get(ranges)! : ranges || this.getRanges();
|
||||
this.verifyReferenceGroups(ranges, [{ definition, ranges }]);
|
||||
@@ -1328,7 +1348,11 @@ namespace FourSlash {
|
||||
if (options) {
|
||||
this.configure(options);
|
||||
}
|
||||
return this.languageService.getCompletionsAtPosition(this.activeFile.fileName, this.currentCaretPosition, options);
|
||||
return this.languageService.getCompletionsAtPosition(
|
||||
this.activeFile.fileName,
|
||||
this.currentCaretPosition,
|
||||
options,
|
||||
this.formatCodeSettings);
|
||||
}
|
||||
|
||||
private getCompletionEntryDetails(entryName: string, source: string | undefined, data: ts.CompletionEntryData | undefined, preferences?: ts.UserPreferences): ts.CompletionEntryDetails | undefined {
|
||||
@@ -1338,10 +1362,6 @@ namespace FourSlash {
|
||||
return this.languageService.getCompletionEntryDetails(this.activeFile.fileName, this.currentCaretPosition, entryName, this.formatCodeSettings, source, preferences, data);
|
||||
}
|
||||
|
||||
private getReferencesAtCaret() {
|
||||
return this.languageService.getReferencesAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
}
|
||||
|
||||
private findReferencesAtCaret() {
|
||||
return this.languageService.findReferences(this.activeFile.fileName, this.currentCaretPosition);
|
||||
}
|
||||
@@ -1377,11 +1397,11 @@ namespace FourSlash {
|
||||
}));
|
||||
}
|
||||
|
||||
public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string) {
|
||||
public verifyQuickInfoAt(markerName: string | Range, expectedText: string, expectedDocumentation?: string, expectedTags?: {name: string; text: string;}[]) {
|
||||
if (typeof markerName === "string") this.goToMarker(markerName);
|
||||
else this.goToRangeStart(markerName);
|
||||
|
||||
this.verifyQuickInfoString(expectedText, expectedDocumentation);
|
||||
this.verifyQuickInfoString(expectedText, expectedDocumentation, expectedTags);
|
||||
}
|
||||
|
||||
public verifyQuickInfos(namesAndTexts: { [name: string]: string | [string, string] }) {
|
||||
@@ -1400,16 +1420,29 @@ namespace FourSlash {
|
||||
}
|
||||
}
|
||||
|
||||
public verifyQuickInfoString(expectedText: string, expectedDocumentation?: string) {
|
||||
public verifyQuickInfoString(expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
|
||||
if (expectedDocumentation === "") {
|
||||
throw new Error("Use 'undefined' instead");
|
||||
throw new Error("Use 'undefined' instead of empty string for `expectedDocumentation`");
|
||||
}
|
||||
const actualQuickInfo = this.languageService.getQuickInfoAtPosition(this.activeFile.fileName, this.currentCaretPosition);
|
||||
const actualQuickInfoText = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.displayParts) : "";
|
||||
const actualQuickInfoDocumentation = actualQuickInfo ? ts.displayPartsToString(actualQuickInfo.documentation) : "";
|
||||
const actualQuickInfoText = ts.displayPartsToString(actualQuickInfo?.displayParts);
|
||||
const actualQuickInfoDocumentation = ts.displayPartsToString(actualQuickInfo?.documentation);
|
||||
const actualQuickInfoTags = actualQuickInfo?.tags?.map(tag => ({ name: tag.name, text: ts.displayPartsToString(tag.text) }));
|
||||
|
||||
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
|
||||
assert.equal(actualQuickInfoDocumentation, expectedDocumentation || "", this.assertionMessageAtLastKnownMarker("quick info doc"));
|
||||
if (!expectedTags) {
|
||||
// Skip if `expectedTags` is not given
|
||||
}
|
||||
else if (!actualQuickInfoTags) {
|
||||
assert.equal(actualQuickInfoTags, expectedTags, this.messageAtLastKnownMarker("QuickInfo tags"));
|
||||
}
|
||||
else {
|
||||
ts.zipWith(expectedTags, actualQuickInfoTags, (expectedTag, actualTag) => {
|
||||
assert.equal(expectedTag.name, actualTag.name);
|
||||
assert.equal(expectedTag.text, actualTag.text, this.messageAtLastKnownMarker("QuickInfo tag " + actualTag.name));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public verifyQuickInfoDisplayParts(kind: string, kindModifiers: string, textSpan: TextSpan,
|
||||
@@ -1927,7 +1960,7 @@ namespace FourSlash {
|
||||
}
|
||||
|
||||
public baselineSyntacticAndSemanticDiagnostics() {
|
||||
const files = this.getCompilerTestFiles();
|
||||
const files = ts.filter(this.getCompilerTestFiles(), f => !ts.endsWith(f.unitName, ".json"));
|
||||
const result = this.getSyntacticDiagnosticBaselineText(files)
|
||||
+ Harness.IO.newLine()
|
||||
+ Harness.IO.newLine()
|
||||
@@ -3113,11 +3146,12 @@ namespace FourSlash {
|
||||
});
|
||||
}
|
||||
|
||||
public verifyImportFixModuleSpecifiers(markerName: string, moduleSpecifiers: string[]) {
|
||||
public verifyImportFixModuleSpecifiers(markerName: string, moduleSpecifiers: string[], preferences?: ts.UserPreferences) {
|
||||
const marker = this.getMarkerByName(markerName);
|
||||
const codeFixes = this.getCodeFixes(marker.fileName, ts.Diagnostics.Cannot_find_name_0.code, {
|
||||
includeCompletionsForModuleExports: true,
|
||||
includeCompletionsWithInsertText: true
|
||||
includeCompletionsWithInsertText: true,
|
||||
...preferences,
|
||||
}, marker.position).filter(f => f.fixName === ts.codefix.importFixName);
|
||||
|
||||
const actualModuleSpecifiers = ts.mapDefined(codeFixes, fix => {
|
||||
|
||||
@@ -255,16 +255,16 @@ namespace FourSlashInterface {
|
||||
}
|
||||
}
|
||||
|
||||
public getInlayHints(expected: readonly VerifyInlayHintsOptions[], span: ts.TextSpan, preference?: ts.InlayHintsOptions) {
|
||||
public getInlayHints(expected: readonly VerifyInlayHintsOptions[], span: ts.TextSpan, preference?: ts.UserPreferences) {
|
||||
this.state.verifyInlayHints(expected, span, preference);
|
||||
}
|
||||
|
||||
public quickInfoIs(expectedText: string, expectedDocumentation?: string) {
|
||||
this.state.verifyQuickInfoString(expectedText, expectedDocumentation);
|
||||
public quickInfoIs(expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
|
||||
this.state.verifyQuickInfoString(expectedText, expectedDocumentation, expectedTags);
|
||||
}
|
||||
|
||||
public quickInfoAt(markerName: string | FourSlash.Range, expectedText: string, expectedDocumentation?: string) {
|
||||
this.state.verifyQuickInfoAt(markerName, expectedText, expectedDocumentation);
|
||||
public quickInfoAt(markerName: string | FourSlash.Range, expectedText: string, expectedDocumentation?: string, expectedTags?: { name: string; text: string; }[]) {
|
||||
this.state.verifyQuickInfoAt(markerName, expectedText, expectedDocumentation, expectedTags);
|
||||
}
|
||||
|
||||
public quickInfos(namesAndTexts: { [name: string]: string }) {
|
||||
@@ -356,18 +356,6 @@ namespace FourSlashInterface {
|
||||
this.state.verifyBaselineGetFileReferences(fileName);
|
||||
}
|
||||
|
||||
public referenceGroups(starts: ArrayOrSingle<string> | ArrayOrSingle<FourSlash.Range>, parts: ReferenceGroup[]) {
|
||||
this.state.verifyReferenceGroups(starts, parts);
|
||||
}
|
||||
|
||||
public noReferences(markerNameOrRange?: string | FourSlash.Range) {
|
||||
this.state.verifyNoReferences(markerNameOrRange);
|
||||
}
|
||||
|
||||
public getReferencesForServerTest(expected: readonly ts.ReferenceEntry[]) {
|
||||
this.state.verifyGetReferencesForServerTest(expected);
|
||||
}
|
||||
|
||||
public singleReferenceGroup(definition: ReferenceGroupDefinition, ranges?: FourSlash.Range[] | string) {
|
||||
this.state.verifySingleReferenceGroup(definition, ranges);
|
||||
}
|
||||
@@ -490,8 +478,8 @@ namespace FourSlashInterface {
|
||||
this.state.verifyImportFixAtPosition(expectedTextArray, errorCode, preferences);
|
||||
}
|
||||
|
||||
public importFixModuleSpecifiers(marker: string, moduleSpecifiers: string[]) {
|
||||
this.state.verifyImportFixModuleSpecifiers(marker, moduleSpecifiers);
|
||||
public importFixModuleSpecifiers(marker: string, moduleSpecifiers: string[], preferences?: ts.UserPreferences) {
|
||||
this.state.verifyImportFixModuleSpecifiers(marker, moduleSpecifiers, preferences);
|
||||
}
|
||||
|
||||
public navigationBar(json: any, options?: { checkSpans?: boolean }) {
|
||||
@@ -1036,8 +1024,48 @@ namespace FourSlashInterface {
|
||||
export const keywordsWithUndefined: readonly ExpectedCompletionEntryObject[] = res;
|
||||
export const keywords: readonly ExpectedCompletionEntryObject[] = keywordsWithUndefined.filter(k => k.name !== "undefined");
|
||||
|
||||
export const typeKeywords: readonly ExpectedCompletionEntryObject[] =
|
||||
["false", "null", "true", "void", "asserts", "any", "boolean", "infer", "keyof", "never", "readonly", "number", "object", "string", "symbol", "undefined", "unique", "unknown", "bigint"].map(keywordEntry);
|
||||
export const typeKeywords: readonly ExpectedCompletionEntryObject[] = [
|
||||
"any",
|
||||
"asserts",
|
||||
"bigint",
|
||||
"boolean",
|
||||
"false",
|
||||
"infer",
|
||||
"keyof",
|
||||
"never",
|
||||
"null",
|
||||
"number",
|
||||
"object",
|
||||
"readonly",
|
||||
"string",
|
||||
"symbol",
|
||||
"true",
|
||||
"undefined",
|
||||
"unique",
|
||||
"unknown",
|
||||
"void",
|
||||
].map(keywordEntry);
|
||||
|
||||
export function sorted(entries: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] {
|
||||
return ts.stableSort(entries, compareExpectedCompletionEntries);
|
||||
}
|
||||
|
||||
// If you want to use a function like `globalsPlus`, that function needs to sort
|
||||
// the concatted array since the entries provided as "plus" could be interleaved
|
||||
// among the "globals." However, we still want to assert that the "plus" array
|
||||
// was internally sorted correctly, so we tack it onto the sorted concatted array
|
||||
// so `verify.completions` can assert that it represents the same order as the response.
|
||||
function combineExpectedCompletionEntries(
|
||||
functionName: string,
|
||||
providedByHarness: readonly ExpectedCompletionEntry[],
|
||||
providedByTest: readonly ExpectedCompletionEntry[],
|
||||
): ExpectedExactCompletionsPlus {
|
||||
return Object.assign(sorted([...providedByHarness, ...providedByTest]), { plusFunctionName: functionName, plusArgument: providedByTest });
|
||||
}
|
||||
|
||||
export function typeKeywordsPlus(plus: readonly ExpectedCompletionEntry[]) {
|
||||
return combineExpectedCompletionEntries("typeKeywordsPlus", typeKeywords, plus);
|
||||
}
|
||||
|
||||
const globalTypeDecls: readonly ExpectedCompletionEntryObject[] = [
|
||||
interfaceEntry("Symbol"),
|
||||
@@ -1061,6 +1089,8 @@ namespace FourSlashInterface {
|
||||
interfaceEntry("NumberConstructor"),
|
||||
interfaceEntry("TemplateStringsArray"),
|
||||
interfaceEntry("ImportMeta"),
|
||||
interfaceEntry("ImportCallOptions"),
|
||||
interfaceEntry("ImportAssertions"),
|
||||
varEntry("Math"),
|
||||
varEntry("Date"),
|
||||
interfaceEntry("DateConstructor"),
|
||||
@@ -1095,6 +1125,7 @@ namespace FourSlashInterface {
|
||||
typeEntry("PromiseConstructorLike"),
|
||||
interfaceEntry("PromiseLike"),
|
||||
interfaceEntry("Promise"),
|
||||
typeEntry("Awaited"),
|
||||
interfaceEntry("ArrayLike"),
|
||||
typeEntry("Partial"),
|
||||
typeEntry("Required"),
|
||||
@@ -1148,13 +1179,12 @@ namespace FourSlashInterface {
|
||||
sortText: SortText.GlobalsOrKeywords
|
||||
};
|
||||
export const globalTypes = globalTypesPlus([]);
|
||||
export function globalTypesPlus(plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] {
|
||||
return [
|
||||
globalThisEntry,
|
||||
...globalTypeDecls,
|
||||
...plus,
|
||||
...typeKeywords,
|
||||
];
|
||||
export function globalTypesPlus(plus: readonly ExpectedCompletionEntry[]) {
|
||||
return combineExpectedCompletionEntries(
|
||||
"globalTypesPlus",
|
||||
[globalThisEntry, ...globalTypeDecls, ...typeKeywords],
|
||||
plus
|
||||
);
|
||||
}
|
||||
|
||||
export const typeAssertionKeywords: readonly ExpectedCompletionEntry[] =
|
||||
@@ -1197,13 +1227,25 @@ namespace FourSlashInterface {
|
||||
});
|
||||
}
|
||||
|
||||
export const classElementKeywords: readonly ExpectedCompletionEntryObject[] =
|
||||
["private", "protected", "public", "static", "abstract", "async", "constructor", "declare", "get", "readonly", "set", "override"].map(keywordEntry);
|
||||
export const classElementKeywords: readonly ExpectedCompletionEntryObject[] = [
|
||||
"abstract",
|
||||
"async",
|
||||
"constructor",
|
||||
"declare",
|
||||
"get",
|
||||
"override",
|
||||
"private",
|
||||
"protected",
|
||||
"public",
|
||||
"readonly",
|
||||
"set",
|
||||
"static",
|
||||
].map(keywordEntry);
|
||||
|
||||
export const classElementInJsKeywords = getInJsKeywords(classElementKeywords);
|
||||
|
||||
export const constructorParameterKeywords: readonly ExpectedCompletionEntryObject[] =
|
||||
["private", "protected", "public", "readonly", "override"].map((name): ExpectedCompletionEntryObject => ({
|
||||
["override", "private", "protected", "public", "readonly"].map((name): ExpectedCompletionEntryObject => ({
|
||||
name,
|
||||
kind: "keyword",
|
||||
sortText: SortText.GlobalsOrKeywords
|
||||
@@ -1217,7 +1259,11 @@ namespace FourSlashInterface {
|
||||
propertyEntry("length"),
|
||||
{ name: "arguments", kind: "property", kindModifiers: "declare", text: "(property) Function.arguments: any" },
|
||||
propertyEntry("caller"),
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
export function functionMembersPlus(plus: readonly ExpectedCompletionEntryObject[]) {
|
||||
return combineExpectedCompletionEntries("functionMembersPlus", functionMembers, plus);
|
||||
}
|
||||
|
||||
export const stringMembers: readonly ExpectedCompletionEntryObject[] = [
|
||||
methodEntry("toString"),
|
||||
@@ -1241,16 +1287,27 @@ namespace FourSlashInterface {
|
||||
propertyEntry("length"),
|
||||
deprecatedMethodEntry("substr"),
|
||||
methodEntry("valueOf"),
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
export const functionMembersWithPrototype: readonly ExpectedCompletionEntryObject[] = [
|
||||
...functionMembers.slice(0, 4),
|
||||
...functionMembers,
|
||||
propertyEntry("prototype"),
|
||||
...functionMembers.slice(4),
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
export function functionMembersWithPrototypePlus(plus: readonly ExpectedCompletionEntryObject[]) {
|
||||
return [...functionMembersWithPrototype, ...plus].sort(compareExpectedCompletionEntries);
|
||||
}
|
||||
|
||||
// TODO: Shouldn't propose type keywords in statement position
|
||||
export const statementKeywordsWithTypes: readonly ExpectedCompletionEntryObject[] = [
|
||||
"abstract",
|
||||
"any",
|
||||
"as",
|
||||
"asserts",
|
||||
"async",
|
||||
"await",
|
||||
"bigint",
|
||||
"boolean",
|
||||
"break",
|
||||
"case",
|
||||
"catch",
|
||||
@@ -1258,6 +1315,7 @@ namespace FourSlashInterface {
|
||||
"const",
|
||||
"continue",
|
||||
"debugger",
|
||||
"declare",
|
||||
"default",
|
||||
"delete",
|
||||
"do",
|
||||
@@ -1270,50 +1328,41 @@ namespace FourSlashInterface {
|
||||
"for",
|
||||
"function",
|
||||
"if",
|
||||
"implements",
|
||||
"import",
|
||||
"in",
|
||||
"infer",
|
||||
"instanceof",
|
||||
"interface",
|
||||
"keyof",
|
||||
"let",
|
||||
"module",
|
||||
"namespace",
|
||||
"never",
|
||||
"new",
|
||||
"null",
|
||||
"number",
|
||||
"object",
|
||||
"package",
|
||||
"readonly",
|
||||
"return",
|
||||
"string",
|
||||
"super",
|
||||
"switch",
|
||||
"symbol",
|
||||
"this",
|
||||
"throw",
|
||||
"true",
|
||||
"try",
|
||||
"type",
|
||||
"typeof",
|
||||
"unique",
|
||||
"unknown",
|
||||
"var",
|
||||
"void",
|
||||
"while",
|
||||
"with",
|
||||
"implements",
|
||||
"interface",
|
||||
"let",
|
||||
"package",
|
||||
"yield",
|
||||
"abstract",
|
||||
"as",
|
||||
"asserts",
|
||||
"any",
|
||||
"async",
|
||||
"await",
|
||||
"boolean",
|
||||
"declare",
|
||||
"infer",
|
||||
"keyof",
|
||||
"module",
|
||||
"namespace",
|
||||
"never",
|
||||
"readonly",
|
||||
"number",
|
||||
"object",
|
||||
"string",
|
||||
"symbol",
|
||||
"type",
|
||||
"unique",
|
||||
"unknown",
|
||||
"bigint",
|
||||
].map(keywordEntry);
|
||||
|
||||
export const statementKeywords: readonly ExpectedCompletionEntryObject[] = statementKeywordsWithTypes.filter(k => {
|
||||
@@ -1335,51 +1384,54 @@ namespace FourSlashInterface {
|
||||
export const statementInJsKeywords = getInJsKeywords(statementKeywords);
|
||||
|
||||
export const globalsVars: readonly ExpectedCompletionEntryObject[] = [
|
||||
functionEntry("eval"),
|
||||
functionEntry("parseInt"),
|
||||
functionEntry("parseFloat"),
|
||||
functionEntry("isNaN"),
|
||||
functionEntry("isFinite"),
|
||||
varEntry("Array"),
|
||||
varEntry("ArrayBuffer"),
|
||||
varEntry("Boolean"),
|
||||
varEntry("DataView"),
|
||||
varEntry("Date"),
|
||||
functionEntry("decodeURI"),
|
||||
functionEntry("decodeURIComponent"),
|
||||
functionEntry("encodeURI"),
|
||||
functionEntry("encodeURIComponent"),
|
||||
deprecatedFunctionEntry("escape"),
|
||||
deprecatedFunctionEntry("unescape"),
|
||||
varEntry("NaN"),
|
||||
varEntry("Infinity"),
|
||||
varEntry("Object"),
|
||||
varEntry("Function"),
|
||||
varEntry("String"),
|
||||
varEntry("Boolean"),
|
||||
varEntry("Number"),
|
||||
varEntry("Math"),
|
||||
varEntry("Date"),
|
||||
varEntry("RegExp"),
|
||||
varEntry("Error"),
|
||||
deprecatedFunctionEntry("escape"),
|
||||
functionEntry("eval"),
|
||||
varEntry("EvalError"),
|
||||
varEntry("RangeError"),
|
||||
varEntry("ReferenceError"),
|
||||
varEntry("SyntaxError"),
|
||||
varEntry("TypeError"),
|
||||
varEntry("URIError"),
|
||||
varEntry("JSON"),
|
||||
varEntry("Array"),
|
||||
varEntry("ArrayBuffer"),
|
||||
varEntry("DataView"),
|
||||
varEntry("Int8Array"),
|
||||
varEntry("Uint8Array"),
|
||||
varEntry("Uint8ClampedArray"),
|
||||
varEntry("Int16Array"),
|
||||
varEntry("Uint16Array"),
|
||||
varEntry("Int32Array"),
|
||||
varEntry("Uint32Array"),
|
||||
varEntry("Float32Array"),
|
||||
varEntry("Float64Array"),
|
||||
varEntry("Function"),
|
||||
varEntry("Infinity"),
|
||||
moduleEntry("Intl"),
|
||||
varEntry("Int16Array"),
|
||||
varEntry("Int32Array"),
|
||||
varEntry("Int8Array"),
|
||||
functionEntry("isFinite"),
|
||||
functionEntry("isNaN"),
|
||||
varEntry("JSON"),
|
||||
varEntry("Math"),
|
||||
varEntry("NaN"),
|
||||
varEntry("Number"),
|
||||
varEntry("Object"),
|
||||
functionEntry("parseFloat"),
|
||||
functionEntry("parseInt"),
|
||||
varEntry("RangeError"),
|
||||
varEntry("ReferenceError"),
|
||||
varEntry("RegExp"),
|
||||
varEntry("String"),
|
||||
varEntry("SyntaxError"),
|
||||
varEntry("TypeError"),
|
||||
varEntry("Uint16Array"),
|
||||
varEntry("Uint32Array"),
|
||||
varEntry("Uint8Array"),
|
||||
varEntry("Uint8ClampedArray"),
|
||||
deprecatedFunctionEntry("unescape"),
|
||||
varEntry("URIError"),
|
||||
];
|
||||
|
||||
const globalKeywordsInsideFunction: readonly ExpectedCompletionEntryObject[] = [
|
||||
"as",
|
||||
"async",
|
||||
"await",
|
||||
"break",
|
||||
"case",
|
||||
"catch",
|
||||
@@ -1399,11 +1451,15 @@ namespace FourSlashInterface {
|
||||
"for",
|
||||
"function",
|
||||
"if",
|
||||
"implements",
|
||||
"import",
|
||||
"in",
|
||||
"instanceof",
|
||||
"interface",
|
||||
"let",
|
||||
"new",
|
||||
"null",
|
||||
"package",
|
||||
"return",
|
||||
"super",
|
||||
"switch",
|
||||
@@ -1416,45 +1472,54 @@ namespace FourSlashInterface {
|
||||
"void",
|
||||
"while",
|
||||
"with",
|
||||
"implements",
|
||||
"interface",
|
||||
"let",
|
||||
"package",
|
||||
"yield",
|
||||
"as",
|
||||
"async",
|
||||
"await",
|
||||
].map(keywordEntry);
|
||||
|
||||
function compareExpectedCompletionEntries(a: ExpectedCompletionEntry, b: ExpectedCompletionEntry) {
|
||||
const aSortText = typeof a !== "string" && a.sortText || ts.Completions.SortText.LocationPriority;
|
||||
const bSortText = typeof b !== "string" && b.sortText || ts.Completions.SortText.LocationPriority;
|
||||
const bySortText = ts.compareStringsCaseSensitiveUI(aSortText, bSortText);
|
||||
if (bySortText !== ts.Comparison.EqualTo) return bySortText;
|
||||
return ts.compareStringsCaseSensitiveUI(typeof a === "string" ? a : a.name, typeof b === "string" ? b : b.name);
|
||||
}
|
||||
|
||||
export const undefinedVarEntry: ExpectedCompletionEntryObject = {
|
||||
name: "undefined",
|
||||
kind: "var",
|
||||
sortText: SortText.GlobalsOrKeywords
|
||||
};
|
||||
// TODO: many of these are inappropriate to always provide
|
||||
export const globalsInsideFunction = (plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] => [
|
||||
export const globalsInsideFunction = (plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }): readonly ExpectedCompletionEntry[] => [
|
||||
{ name: "arguments", kind: "local var" },
|
||||
...plus,
|
||||
globalThisEntry,
|
||||
...globalsVars,
|
||||
...options?.noLib ? [] : globalsVars,
|
||||
undefinedVarEntry,
|
||||
...globalKeywordsInsideFunction,
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
const globalInJsKeywordsInsideFunction = getInJsKeywords(globalKeywordsInsideFunction);
|
||||
|
||||
// TODO: many of these are inappropriate to always provide
|
||||
export const globalsInJsInsideFunction = (plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] => [
|
||||
export const globalsInJsInsideFunction = (plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }): readonly ExpectedCompletionEntry[] => [
|
||||
{ name: "arguments", kind: "local var" },
|
||||
globalThisEntry,
|
||||
...globalsVars,
|
||||
...options?.noLib ? [] : globalsVars,
|
||||
...plus,
|
||||
undefinedVarEntry,
|
||||
...globalInJsKeywordsInsideFunction,
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
// TODO: many of these are inappropriate to always provide
|
||||
export const globalKeywords: readonly ExpectedCompletionEntryObject[] = [
|
||||
"abstract",
|
||||
"any",
|
||||
"as",
|
||||
"asserts",
|
||||
"async",
|
||||
"await",
|
||||
"bigint",
|
||||
"boolean",
|
||||
"break",
|
||||
"case",
|
||||
"catch",
|
||||
@@ -1462,6 +1527,7 @@ namespace FourSlashInterface {
|
||||
"const",
|
||||
"continue",
|
||||
"debugger",
|
||||
"declare",
|
||||
"default",
|
||||
"delete",
|
||||
"do",
|
||||
@@ -1474,55 +1540,49 @@ namespace FourSlashInterface {
|
||||
"for",
|
||||
"function",
|
||||
"if",
|
||||
"implements",
|
||||
"import",
|
||||
"in",
|
||||
"infer",
|
||||
"instanceof",
|
||||
"interface",
|
||||
"keyof",
|
||||
"let",
|
||||
"module",
|
||||
"namespace",
|
||||
"never",
|
||||
"new",
|
||||
"null",
|
||||
"number",
|
||||
"object",
|
||||
"package",
|
||||
"readonly",
|
||||
"return",
|
||||
"string",
|
||||
"super",
|
||||
"switch",
|
||||
"symbol",
|
||||
"this",
|
||||
"throw",
|
||||
"true",
|
||||
"try",
|
||||
"type",
|
||||
"typeof",
|
||||
"unique",
|
||||
"unknown",
|
||||
"var",
|
||||
"void",
|
||||
"while",
|
||||
"with",
|
||||
"implements",
|
||||
"interface",
|
||||
"let",
|
||||
"package",
|
||||
"yield",
|
||||
"abstract",
|
||||
"as",
|
||||
"asserts",
|
||||
"any",
|
||||
"async",
|
||||
"await",
|
||||
"boolean",
|
||||
"declare",
|
||||
"infer",
|
||||
"keyof",
|
||||
"module",
|
||||
"namespace",
|
||||
"never",
|
||||
"readonly",
|
||||
"number",
|
||||
"object",
|
||||
"string",
|
||||
"symbol",
|
||||
"type",
|
||||
"unique",
|
||||
"unknown",
|
||||
"bigint",
|
||||
].map(keywordEntry);
|
||||
|
||||
export const globalInJsKeywords = getInJsKeywords(globalKeywords);
|
||||
|
||||
export const insideMethodKeywords: readonly ExpectedCompletionEntryObject[] = [
|
||||
"as",
|
||||
"async",
|
||||
"await",
|
||||
"break",
|
||||
"case",
|
||||
"catch",
|
||||
@@ -1542,11 +1602,15 @@ namespace FourSlashInterface {
|
||||
"for",
|
||||
"function",
|
||||
"if",
|
||||
"implements",
|
||||
"import",
|
||||
"in",
|
||||
"instanceof",
|
||||
"interface",
|
||||
"let",
|
||||
"new",
|
||||
"null",
|
||||
"package",
|
||||
"return",
|
||||
"super",
|
||||
"switch",
|
||||
@@ -1559,14 +1623,7 @@ namespace FourSlashInterface {
|
||||
"void",
|
||||
"while",
|
||||
"with",
|
||||
"implements",
|
||||
"interface",
|
||||
"let",
|
||||
"package",
|
||||
"yield",
|
||||
"as",
|
||||
"async",
|
||||
"await",
|
||||
].map(keywordEntry);
|
||||
|
||||
export const insideMethodInJsKeywords = getInJsKeywords(insideMethodKeywords);
|
||||
@@ -1576,34 +1633,31 @@ namespace FourSlashInterface {
|
||||
...globalsVars,
|
||||
undefinedVarEntry,
|
||||
...globalKeywords
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
export const globalsInJs: readonly ExpectedCompletionEntryObject[] = [
|
||||
globalThisEntry,
|
||||
...globalsVars,
|
||||
undefinedVarEntry,
|
||||
...globalInJsKeywords
|
||||
];
|
||||
].sort(compareExpectedCompletionEntries);
|
||||
|
||||
export function globalsPlus(plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] {
|
||||
const firstEntry = plus[0];
|
||||
const afterUndefined = typeof firstEntry !== "string" && firstEntry.sortText! > undefinedVarEntry.sortText!;
|
||||
return [
|
||||
export function globalsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }) {
|
||||
return combineExpectedCompletionEntries("globalsPlus", [
|
||||
globalThisEntry,
|
||||
...globalsVars,
|
||||
...afterUndefined ? ts.emptyArray : plus,
|
||||
...options?.noLib ? [] : globalsVars,
|
||||
undefinedVarEntry,
|
||||
...afterUndefined ? plus : ts.emptyArray,
|
||||
...globalKeywords];
|
||||
...globalKeywords,
|
||||
], plus);
|
||||
}
|
||||
|
||||
export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[]): readonly ExpectedCompletionEntry[] {
|
||||
return [
|
||||
export function globalsInJsPlus(plus: readonly ExpectedCompletionEntry[], options?: { noLib?: boolean }) {
|
||||
return combineExpectedCompletionEntries("globalsInJsPlus", [
|
||||
globalThisEntry,
|
||||
...globalsVars,
|
||||
...plus,
|
||||
...options?.noLib ? [] : globalsVars,
|
||||
undefinedVarEntry,
|
||||
...globalInJsKeywords];
|
||||
...globalInJsKeywords,
|
||||
], plus);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1642,12 +1696,18 @@ namespace FourSlashInterface {
|
||||
readonly sortText?: ts.Completions.SortText;
|
||||
}
|
||||
|
||||
export type ExpectedExactCompletionsPlus = readonly ExpectedCompletionEntry[] & {
|
||||
plusFunctionName: string,
|
||||
plusArgument: readonly ExpectedCompletionEntry[]
|
||||
};
|
||||
|
||||
export interface VerifyCompletionsOptions {
|
||||
readonly marker?: ArrayOrSingle<string | FourSlash.Marker>;
|
||||
readonly isNewIdentifierLocation?: boolean; // Always tested
|
||||
readonly isGlobalCompletion?: boolean; // Only tested if set
|
||||
readonly optionalReplacementSpan?: FourSlash.Range; // Only tested if set
|
||||
readonly exact?: ArrayOrSingle<ExpectedCompletionEntry>;
|
||||
readonly exact?: ArrayOrSingle<ExpectedCompletionEntry> | ExpectedExactCompletionsPlus;
|
||||
readonly unsorted?: readonly ExpectedCompletionEntry[];
|
||||
readonly includes?: ArrayOrSingle<ExpectedCompletionEntry>;
|
||||
readonly excludes?: ArrayOrSingle<string>;
|
||||
readonly preferences?: ts.UserPreferences;
|
||||
|
||||
+14
-13
@@ -41,6 +41,7 @@ namespace Harness {
|
||||
export const virtualFileSystemRoot = "/";
|
||||
|
||||
function createNodeIO(): IO {
|
||||
const workspaceRoot = Utils.findUpRoot();
|
||||
let fs: any, pathModule: any;
|
||||
if (require) {
|
||||
fs = require("fs");
|
||||
@@ -154,7 +155,7 @@ namespace Harness {
|
||||
log: s => console.log(s),
|
||||
args: () => ts.sys.args,
|
||||
getExecutingFilePath: () => ts.sys.getExecutingFilePath(),
|
||||
getWorkspaceRoot: () => vpath.resolve(__dirname, "../.."),
|
||||
getWorkspaceRoot: () => workspaceRoot,
|
||||
exit: exitCode => ts.sys.exit(exitCode),
|
||||
readDirectory: (path, extension, exclude, include, depth) => ts.sys.readDirectory(path, extension, exclude, include, depth),
|
||||
getAccessibleFileSystemEntries,
|
||||
@@ -271,7 +272,7 @@ namespace Harness {
|
||||
}
|
||||
|
||||
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
|
||||
switch (options.target) {
|
||||
switch (ts.getEmitScriptTarget(options)) {
|
||||
case ts.ScriptTarget.ESNext:
|
||||
case ts.ScriptTarget.ES2017:
|
||||
return "lib.es2017.d.ts";
|
||||
@@ -303,21 +304,21 @@ namespace Harness {
|
||||
|
||||
// Additional options not already in ts.optionDeclarations
|
||||
const harnessOptionDeclarations: ts.CommandLineOption[] = [
|
||||
{ name: "allowNonTsExtensions", type: "boolean" },
|
||||
{ name: "useCaseSensitiveFileNames", type: "boolean" },
|
||||
{ name: "allowNonTsExtensions", type: "boolean", defaultValueDescription: false },
|
||||
{ name: "useCaseSensitiveFileNames", type: "boolean", defaultValueDescription: false },
|
||||
{ name: "baselineFile", type: "string" },
|
||||
{ name: "includeBuiltFile", type: "string" },
|
||||
{ name: "fileName", type: "string" },
|
||||
{ name: "libFiles", type: "string" },
|
||||
{ name: "noErrorTruncation", type: "boolean" },
|
||||
{ name: "suppressOutputPathCheck", type: "boolean" },
|
||||
{ name: "noImplicitReferences", type: "boolean" },
|
||||
{ name: "noErrorTruncation", type: "boolean", defaultValueDescription: false },
|
||||
{ name: "suppressOutputPathCheck", type: "boolean", defaultValueDescription: false },
|
||||
{ name: "noImplicitReferences", type: "boolean", defaultValueDescription: false },
|
||||
{ name: "currentDirectory", type: "string" },
|
||||
{ name: "symlink", type: "string" },
|
||||
{ name: "link", type: "string" },
|
||||
{ name: "noTypesAndSymbols", type: "boolean" },
|
||||
{ name: "noTypesAndSymbols", type: "boolean", defaultValueDescription: false },
|
||||
// Emitted js baseline will print full paths for every output file
|
||||
{ name: "fullEmitPaths", type: "boolean" }
|
||||
{ name: "fullEmitPaths", type: "boolean", defaultValueDescription: false },
|
||||
];
|
||||
|
||||
let optionsIndex: ts.ESMap<string, ts.CommandLineOption>;
|
||||
@@ -391,7 +392,7 @@ namespace Harness {
|
||||
symlinks?: vfs.FileSet
|
||||
): compiler.CompilationResult {
|
||||
const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.cloneCompilerOptions(compilerOptions) : { noResolve: false };
|
||||
options.target = options.target || ts.ScriptTarget.ES3;
|
||||
options.target = ts.getEmitScriptTarget(options);
|
||||
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
|
||||
options.noErrorTruncation = true;
|
||||
options.skipDefaultLibCheck = typeof options.skipDefaultLibCheck === "undefined" ? true : options.skipDefaultLibCheck;
|
||||
@@ -505,7 +506,7 @@ namespace Harness {
|
||||
sourceFileName = outFile;
|
||||
}
|
||||
|
||||
const dTsFileName = ts.removeFileExtension(sourceFileName) + ts.Extension.Dts;
|
||||
const dTsFileName = ts.removeFileExtension(sourceFileName) + ts.getDeclarationEmitExtensionForPath(sourceFileName);
|
||||
return result.dts.get(dTsFileName);
|
||||
}
|
||||
|
||||
@@ -536,7 +537,7 @@ namespace Harness {
|
||||
outputLines += content;
|
||||
}
|
||||
if (pretty) {
|
||||
outputLines += ts.getErrorSummaryText(ts.getErrorCountForSummary(diagnostics), IO.newLine());
|
||||
outputLines += ts.getErrorSummaryText(ts.getErrorCountForSummary(diagnostics), ts.getFilesInErrorForSummary(diagnostics), IO.newLine(), { getCurrentDirectory: () => "" });
|
||||
}
|
||||
return outputLines;
|
||||
}
|
||||
@@ -897,7 +898,7 @@ namespace Harness {
|
||||
jsCode += "\r\n";
|
||||
}
|
||||
if (!result.diagnostics.length && !ts.endsWith(file.file, ts.Extension.Json)) {
|
||||
const fileParseResult = ts.createSourceFile(file.file, file.text, options.target || ts.ScriptTarget.ES3, /*parentNodes*/ false, ts.endsWith(file.file, "x") ? ts.ScriptKind.JSX : ts.ScriptKind.JS);
|
||||
const fileParseResult = ts.createSourceFile(file.file, file.text, ts.getEmitScriptTarget(options), /*parentNodes*/ false, ts.endsWith(file.file, "x") ? ts.ScriptKind.JSX : ts.ScriptKind.JS);
|
||||
if (ts.length(fileParseResult.parseDiagnostics)) {
|
||||
jsCode += getErrorBaseline([file.asTestFile()], fileParseResult.parseDiagnostics);
|
||||
return;
|
||||
|
||||
@@ -472,8 +472,8 @@ namespace Harness.LanguageService {
|
||||
const responseFormat = format || ts.SemanticClassificationFormat.Original;
|
||||
return unwrapJSONCallResult(this.shim.getEncodedSemanticClassifications(fileName, span.start, span.length, responseFormat));
|
||||
}
|
||||
getCompletionsAtPosition(fileName: string, position: number, preferences: ts.UserPreferences | undefined): ts.CompletionInfo {
|
||||
return unwrapJSONCallResult(this.shim.getCompletionsAtPosition(fileName, position, preferences));
|
||||
getCompletionsAtPosition(fileName: string, position: number, preferences: ts.UserPreferences | undefined, formattingSettings: ts.FormatCodeSettings | undefined): ts.CompletionInfo {
|
||||
return unwrapJSONCallResult(this.shim.getCompletionsAtPosition(fileName, position, preferences, formattingSettings));
|
||||
}
|
||||
getCompletionEntryDetails(fileName: string, position: number, entryName: string, formatOptions: ts.FormatCodeOptions | undefined, source: string | undefined, preferences: ts.UserPreferences | undefined, data: ts.CompletionEntryData | undefined): ts.CompletionEntryDetails {
|
||||
return unwrapJSONCallResult(this.shim.getCompletionEntryDetails(fileName, position, entryName, JSON.stringify(formatOptions), source, preferences, data));
|
||||
@@ -600,7 +600,7 @@ namespace Harness.LanguageService {
|
||||
provideCallHierarchyOutgoingCalls(fileName: string, position: number) {
|
||||
return unwrapJSONCallResult(this.shim.provideCallHierarchyOutgoingCalls(fileName, position));
|
||||
}
|
||||
provideInlayHints(fileName: string, span: ts.TextSpan, preference: ts.InlayHintsOptions) {
|
||||
provideInlayHints(fileName: string, span: ts.TextSpan, preference: ts.UserPreferences) {
|
||||
return unwrapJSONCallResult(this.shim.provideInlayHints(fileName, span, preference));
|
||||
}
|
||||
getEmitOutput(fileName: string): ts.EmitOutput {
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
"evaluatorImpl.ts",
|
||||
"fakesHosts.ts",
|
||||
"client.ts",
|
||||
"findUpDir.ts",
|
||||
|
||||
"runnerbase.ts",
|
||||
"sourceMapRecorder.ts",
|
||||
|
||||
@@ -922,7 +922,7 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
});
|
||||
}
|
||||
return { directories, files };
|
||||
}, path => this.realpath(path), path => this.directoryExists(path));
|
||||
}, path => this.realpath(path));
|
||||
}
|
||||
|
||||
createHash(s: string): string {
|
||||
|
||||
@@ -108,7 +108,7 @@ namespace vpath {
|
||||
}
|
||||
|
||||
export function isDeclaration(path: string) {
|
||||
return extname(path, ".d.ts", /*ignoreCase*/ false).length > 0;
|
||||
return ts.fileExtensionIsOneOf(path, [ts.Extension.Dmts, ts.Extension.Dcts, ts.Extension.Dts]);
|
||||
}
|
||||
|
||||
export function isSourceMap(path: string) {
|
||||
|
||||
+96
-71
@@ -9,7 +9,6 @@ namespace ts.JsTyping {
|
||||
}
|
||||
|
||||
interface PackageJson {
|
||||
_requiredBy?: string[];
|
||||
dependencies?: MapLike<string>;
|
||||
devDependencies?: MapLike<string>;
|
||||
name?: string;
|
||||
@@ -152,17 +151,8 @@ namespace ts.JsTyping {
|
||||
const possibleSearchDirs = new Set(fileNames.map(getDirectoryPath));
|
||||
possibleSearchDirs.add(projectRootPath);
|
||||
possibleSearchDirs.forEach((searchDir) => {
|
||||
const packageJsonPath = combinePaths(searchDir, "package.json");
|
||||
getTypingNamesFromJson(packageJsonPath, filesToWatch);
|
||||
|
||||
const bowerJsonPath = combinePaths(searchDir, "bower.json");
|
||||
getTypingNamesFromJson(bowerJsonPath, filesToWatch);
|
||||
|
||||
const bowerComponentsPath = combinePaths(searchDir, "bower_components");
|
||||
getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
|
||||
|
||||
const nodeModulesPath = combinePaths(searchDir, "node_modules");
|
||||
getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
|
||||
getTypingNames(searchDir, "bower.json", "bower_components", filesToWatch);
|
||||
getTypingNames(searchDir, "package.json", "node_modules", filesToWatch);
|
||||
});
|
||||
if(!typeAcquisition.disableFilenameBasedTypeAcquisition) {
|
||||
getTypingNamesFromSourceFileNames(fileNames);
|
||||
@@ -214,17 +204,104 @@ namespace ts.JsTyping {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the typing info from common package manager json files like package.json or bower.json
|
||||
* Adds inferred typings from manifest/module pairs (think package.json + node_modules)
|
||||
*
|
||||
* @param projectRootPath is the path to the directory where to look for package.json, bower.json and other typing information
|
||||
* @param manifestName is the name of the manifest (package.json or bower.json)
|
||||
* @param modulesDirName is the directory name for modules (node_modules or bower_components). Should be lowercase!
|
||||
* @param filesToWatch are the files to watch for changes. We will push things into this array.
|
||||
*/
|
||||
function getTypingNamesFromJson(jsonPath: string, filesToWatch: Push<string>) {
|
||||
if (!host.fileExists(jsonPath)) {
|
||||
function getTypingNames(projectRootPath: string, manifestName: string, modulesDirName: string, filesToWatch: string[]): void {
|
||||
// First, we check the manifests themselves. They're not
|
||||
// _required_, but they allow us to do some filtering when dealing
|
||||
// with big flat dep directories.
|
||||
const manifestPath = combinePaths(projectRootPath, manifestName);
|
||||
let manifest;
|
||||
let manifestTypingNames;
|
||||
if (host.fileExists(manifestPath)) {
|
||||
filesToWatch.push(manifestPath);
|
||||
manifest = readConfigFile(manifestPath, path => host.readFile(path)).config;
|
||||
manifestTypingNames = flatMap([manifest.dependencies, manifest.devDependencies, manifest.optionalDependencies, manifest.peerDependencies], getOwnKeys);
|
||||
addInferredTypings(manifestTypingNames, `Typing names in '${manifestPath}' dependencies`);
|
||||
}
|
||||
|
||||
// Now we scan the directories for typing information in
|
||||
// already-installed dependencies (if present). Note that this
|
||||
// step happens regardless of whether a manifest was present,
|
||||
// which is certainly a valid configuration, if an unusual one.
|
||||
const packagesFolderPath = combinePaths(projectRootPath, modulesDirName);
|
||||
filesToWatch.push(packagesFolderPath);
|
||||
if (!host.directoryExists(packagesFolderPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
filesToWatch.push(jsonPath);
|
||||
const jsonConfig: PackageJson = readConfigFile(jsonPath, path => host.readFile(path)).config;
|
||||
const jsonTypingNames = flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], getOwnKeys);
|
||||
addInferredTypings(jsonTypingNames, `Typing names in '${jsonPath}' dependencies`);
|
||||
// There's two cases we have to take into account here:
|
||||
// 1. If manifest is undefined, then we're not using a manifest.
|
||||
// That means that we should scan _all_ dependencies at the top
|
||||
// level of the modulesDir.
|
||||
// 2. If manifest is defined, then we can do some special
|
||||
// filtering to reduce the amount of scanning we need to do.
|
||||
//
|
||||
// Previous versions of this algorithm checked for a `_requiredBy`
|
||||
// field in the package.json, but that field is only present in
|
||||
// `npm@>=3 <7`.
|
||||
|
||||
// Package names that do **not** provide their own typings, so
|
||||
// we'll look them up.
|
||||
const packageNames: string[] = [];
|
||||
|
||||
const dependencyManifestNames = manifestTypingNames
|
||||
// This is #1 described above.
|
||||
? manifestTypingNames.map(typingName => combinePaths(packagesFolderPath, typingName, manifestName))
|
||||
// And #2. Depth = 3 because scoped packages look like `node_modules/@foo/bar/package.json`
|
||||
: host.readDirectory(packagesFolderPath, [Extension.Json], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 3)
|
||||
.filter(manifestPath => {
|
||||
if (getBaseFileName(manifestPath) !== manifestName) {
|
||||
return false;
|
||||
}
|
||||
// It's ok to treat
|
||||
// `node_modules/@foo/bar/package.json` as a manifest,
|
||||
// but not `node_modules/jquery/nested/package.json`.
|
||||
// We only assume depth 3 is ok for formally scoped
|
||||
// packages. So that needs this dance here.
|
||||
const pathComponents = getPathComponents(normalizePath(manifestPath));
|
||||
const isScoped = pathComponents[pathComponents.length - 3][0] === "@";
|
||||
return isScoped && pathComponents[pathComponents.length - 4].toLowerCase() === modulesDirName || // `node_modules/@foo/bar`
|
||||
!isScoped && pathComponents[pathComponents.length - 3].toLowerCase() === modulesDirName; // `node_modules/foo`
|
||||
});
|
||||
|
||||
if (log) log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(dependencyManifestNames)}`);
|
||||
|
||||
// Once we have the names of things to look up, we iterate over
|
||||
// and either collect their included typings, or add them to the
|
||||
// list of typings we need to look up separately.
|
||||
for (const manifestPath of dependencyManifestNames) {
|
||||
const normalizedFileName = normalizePath(manifestPath);
|
||||
const result = readConfigFile(normalizedFileName, (path: string) => host.readFile(path));
|
||||
const manifest: PackageJson = result.config;
|
||||
|
||||
// If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
|
||||
// to download d.ts files from DefinitelyTyped
|
||||
if (!manifest.name) {
|
||||
continue;
|
||||
}
|
||||
const ownTypes = manifest.types || manifest.typings;
|
||||
if (ownTypes) {
|
||||
const absolutePath = getNormalizedAbsolutePath(ownTypes, getDirectoryPath(normalizedFileName));
|
||||
if (host.fileExists(absolutePath)) {
|
||||
if (log) log(` Package '${manifest.name}' provides its own types.`);
|
||||
inferredTypings.set(manifest.name, absolutePath);
|
||||
}
|
||||
else {
|
||||
if (log) log(` Package '${manifest.name}' provides its own types but they are missing.`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
packageNames.push(manifest.name);
|
||||
}
|
||||
}
|
||||
|
||||
addInferredTypings(packageNames, " Found package names");
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -251,58 +328,6 @@ namespace ts.JsTyping {
|
||||
addInferredTyping("react");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer typing names from packages folder (ex: node_module, bower_components)
|
||||
* @param packagesFolderPath is the path to the packages folder
|
||||
*/
|
||||
function getTypingNamesFromPackagesFolder(packagesFolderPath: string, filesToWatch: Push<string>) {
|
||||
filesToWatch.push(packagesFolderPath);
|
||||
|
||||
// Todo: add support for ModuleResolutionHost too
|
||||
if (!host.directoryExists(packagesFolderPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
|
||||
const fileNames = host.readDirectory(packagesFolderPath, [Extension.Json], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
|
||||
if (log) log(`Searching for typing names in ${packagesFolderPath}; all files: ${JSON.stringify(fileNames)}`);
|
||||
const packageNames: string[] = [];
|
||||
for (const fileName of fileNames) {
|
||||
const normalizedFileName = normalizePath(fileName);
|
||||
const baseFileName = getBaseFileName(normalizedFileName);
|
||||
if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
|
||||
continue;
|
||||
}
|
||||
const result = readConfigFile(normalizedFileName, (path: string) => host.readFile(path));
|
||||
const packageJson: PackageJson = result.config;
|
||||
|
||||
// npm 3's package.json contains a "_requiredBy" field
|
||||
// we should include all the top level module names for npm 2, and only module names whose
|
||||
// "_requiredBy" field starts with "#" or equals "/" for npm 3.
|
||||
if (baseFileName === "package.json" && packageJson._requiredBy &&
|
||||
filter(packageJson._requiredBy, (r: string) => r[0] === "#" || r === "/").length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
|
||||
// to download d.ts files from DefinitelyTyped
|
||||
if (!packageJson.name) {
|
||||
continue;
|
||||
}
|
||||
const ownTypes = packageJson.types || packageJson.typings;
|
||||
if (ownTypes) {
|
||||
const absolutePath = getNormalizedAbsolutePath(ownTypes, getDirectoryPath(normalizedFileName));
|
||||
if (log) log(` Package '${packageJson.name}' provides its own types.`);
|
||||
inferredTypings.set(packageJson.name, absolutePath);
|
||||
}
|
||||
else {
|
||||
packageNames.push(packageJson.name);
|
||||
}
|
||||
}
|
||||
addInferredTypings(packageNames, " Found package names");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const enum NameValidationResult {
|
||||
|
||||
Vendored
+1068
-2043
File diff suppressed because it is too large
Load Diff
Vendored
+27
-54
@@ -58,17 +58,11 @@ interface FontFaceSet extends Set<FontFace> {
|
||||
|
||||
interface FormData {
|
||||
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
|
||||
/**
|
||||
* Returns an array of key, value pairs for every entry in the list.
|
||||
*/
|
||||
/** Returns an array of key, value pairs for every entry in the list. */
|
||||
entries(): IterableIterator<[string, FormDataEntryValue]>;
|
||||
/**
|
||||
* Returns a list of keys in the list.
|
||||
*/
|
||||
/** Returns a list of keys in the list. */
|
||||
keys(): IterableIterator<string>;
|
||||
/**
|
||||
* Returns a list of values in the list.
|
||||
*/
|
||||
/** Returns a list of values in the list. */
|
||||
values(): IterableIterator<FormDataEntryValue>;
|
||||
}
|
||||
|
||||
@@ -94,24 +88,16 @@ interface HTMLSelectElement {
|
||||
|
||||
interface Headers {
|
||||
[Symbol.iterator](): IterableIterator<[string, string]>;
|
||||
/**
|
||||
* Returns an iterator allowing to go through all key/value pairs contained in this object.
|
||||
*/
|
||||
/** Returns an iterator allowing to go through all key/value pairs contained in this object. */
|
||||
entries(): IterableIterator<[string, string]>;
|
||||
/**
|
||||
* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
|
||||
*/
|
||||
/** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */
|
||||
keys(): IterableIterator<string>;
|
||||
/**
|
||||
* Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
|
||||
*/
|
||||
/** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */
|
||||
values(): IterableIterator<string>;
|
||||
}
|
||||
|
||||
interface IDBDatabase {
|
||||
/**
|
||||
* Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names.
|
||||
*/
|
||||
/** Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names. */
|
||||
transaction(storeNames: string | Iterable<string>, mode?: IDBTransactionMode): IDBTransaction;
|
||||
}
|
||||
|
||||
@@ -149,39 +135,28 @@ interface NamedNodeMap {
|
||||
}
|
||||
|
||||
interface Navigator {
|
||||
/** Available only in secure contexts. */
|
||||
requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: Iterable<MediaKeySystemConfiguration>): Promise<MediaKeySystemAccess>;
|
||||
vibrate(pattern: Iterable<number>): boolean;
|
||||
}
|
||||
|
||||
interface NodeList {
|
||||
[Symbol.iterator](): IterableIterator<Node>;
|
||||
/**
|
||||
* Returns an array of key, value pairs for every entry in the list.
|
||||
*/
|
||||
/** Returns an array of key, value pairs for every entry in the list. */
|
||||
entries(): IterableIterator<[number, Node]>;
|
||||
/**
|
||||
* Returns an list of keys in the list.
|
||||
*/
|
||||
/** Returns an list of keys in the list. */
|
||||
keys(): IterableIterator<number>;
|
||||
/**
|
||||
* Returns an list of values in the list.
|
||||
*/
|
||||
/** Returns an list of values in the list. */
|
||||
values(): IterableIterator<Node>;
|
||||
}
|
||||
|
||||
interface NodeListOf<TNode extends Node> {
|
||||
[Symbol.iterator](): IterableIterator<TNode>;
|
||||
/**
|
||||
* Returns an array of key, value pairs for every entry in the list.
|
||||
*/
|
||||
/** Returns an array of key, value pairs for every entry in the list. */
|
||||
entries(): IterableIterator<[number, TNode]>;
|
||||
/**
|
||||
* Returns an list of keys in the list.
|
||||
*/
|
||||
/** Returns an list of keys in the list. */
|
||||
keys(): IterableIterator<number>;
|
||||
/**
|
||||
* Returns an list of values in the list.
|
||||
*/
|
||||
/** Returns an list of values in the list. */
|
||||
values(): IterableIterator<TNode>;
|
||||
}
|
||||
|
||||
@@ -193,14 +168,11 @@ interface PluginArray {
|
||||
[Symbol.iterator](): IterableIterator<Plugin>;
|
||||
}
|
||||
|
||||
interface RTCStatsReport extends ReadonlyMap<string, any> {
|
||||
interface RTCRtpTransceiver {
|
||||
setCodecPreferences(codecs: Iterable<RTCRtpCodecCapability>): void;
|
||||
}
|
||||
|
||||
interface ReadableStream<R = any> {
|
||||
[Symbol.iterator](): IterableIterator<any>;
|
||||
entries(): IterableIterator<[number, any]>;
|
||||
keys(): IterableIterator<number>;
|
||||
values(): IterableIterator<any>;
|
||||
interface RTCStatsReport extends ReadonlyMap<string, any> {
|
||||
}
|
||||
|
||||
interface SVGLengthList {
|
||||
@@ -263,17 +235,11 @@ interface TouchList {
|
||||
|
||||
interface URLSearchParams {
|
||||
[Symbol.iterator](): IterableIterator<[string, string]>;
|
||||
/**
|
||||
* Returns an array of key, value pairs for every entry in the search params.
|
||||
*/
|
||||
/** Returns an array of key, value pairs for every entry in the search params. */
|
||||
entries(): IterableIterator<[string, string]>;
|
||||
/**
|
||||
* Returns a list of keys in the search params.
|
||||
*/
|
||||
/** Returns a list of keys in the search params. */
|
||||
keys(): IterableIterator<string>;
|
||||
/**
|
||||
* Returns a list of values in the search params.
|
||||
*/
|
||||
/** Returns a list of values in the search params. */
|
||||
values(): IterableIterator<string>;
|
||||
}
|
||||
|
||||
@@ -281,6 +247,13 @@ interface WEBGL_draw_buffers {
|
||||
drawBuffersWEBGL(buffers: Iterable<GLenum>): void;
|
||||
}
|
||||
|
||||
interface WEBGL_multi_draw {
|
||||
multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array | Iterable<GLint>, firstsOffset: GLuint, countsList: Int32Array | Iterable<GLsizei>, countsOffset: GLuint, instanceCountsList: Int32Array | Iterable<GLsizei>, instanceCountsOffset: GLuint, drawcount: GLsizei): void;
|
||||
multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array | Iterable<GLint>, firstsOffset: GLuint, countsList: Int32Array | Iterable<GLsizei>, countsOffset: GLuint, drawcount: GLsizei): void;
|
||||
multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array | Iterable<GLint>, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable<GLsizei>, offsetsOffset: GLuint, instanceCountsList: Int32Array | Iterable<GLsizei>, instanceCountsOffset: GLuint, drawcount: GLsizei): void;
|
||||
multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array | Iterable<GLint>, countsOffset: GLuint, type: GLenum, offsetsList: Int32Array | Iterable<GLsizei>, offsetsOffset: GLuint, drawcount: GLsizei): void;
|
||||
}
|
||||
|
||||
interface WebGL2RenderingContextBase {
|
||||
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: GLuint): void;
|
||||
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: GLuint): void;
|
||||
|
||||
Vendored
+4
-11
@@ -137,7 +137,8 @@ interface ReadonlyMap<K, V> {
|
||||
}
|
||||
|
||||
interface MapConstructor {
|
||||
new <K, V>(iterable: Iterable<readonly [K, V]>): Map<K, V>;
|
||||
new(): Map<any, any>;
|
||||
new <K, V>(iterable?: Iterable<readonly [K, V]> | null): Map<K, V>;
|
||||
}
|
||||
|
||||
interface WeakMap<K extends object, V> { }
|
||||
@@ -203,7 +204,7 @@ interface PromiseConstructor {
|
||||
* @param values An iterable of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
|
||||
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
|
||||
@@ -211,15 +212,7 @@ interface PromiseConstructor {
|
||||
* @param values An iterable of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
race<T>(values: Iterable<T>): Promise<T extends PromiseLike<infer U> ? U : T>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
|
||||
* or rejected.
|
||||
* @param values An iterable of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
|
||||
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
|
||||
}
|
||||
|
||||
interface String {
|
||||
|
||||
Vendored
+2
-74
@@ -18,79 +18,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>]): Promise<[T1, T2, T3, T4]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
* resolve, or rejected when any Promise is rejected.
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T>(values: readonly (T | PromiseLike<T>)[]): Promise<T[]>;
|
||||
all<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>;
|
||||
|
||||
// see: lib.es2015.iterable.d.ts
|
||||
// all<T>(values: Iterable<T | PromiseLike<T>>): Promise<T[]>;
|
||||
@@ -101,7 +29,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
race<T>(values: readonly T[]): Promise<T extends PromiseLike<infer U> ? U : T>;
|
||||
race<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;
|
||||
|
||||
// see: lib.es2015.iterable.d.ts
|
||||
// race<T>(values: Iterable<T>): Promise<T extends PromiseLike<infer U> ? U : T>;
|
||||
|
||||
Vendored
+5
-1
@@ -37,9 +37,13 @@ declare namespace Intl {
|
||||
supportedLocalesOf(locales: string | string[], options?: { localeMatcher?: "lookup" | "best fit" }): string[];
|
||||
};
|
||||
|
||||
// We can only have one definition for 'type' in TypeScript, and so you can learn where the keys come from here:
|
||||
type ES2018NumberFormatPartType = "literal" | "nan" | "infinity" | "percent" | "integer" | "group" | "decimal" | "fraction" | "plusSign" | "minusSign" | "percentSign" | "currency" | "code" | "symbol" | "name";
|
||||
type ES2020NumberFormatPartType = "compact" | "exponentInteger" | "exponentMinusSign" | "exponentSeparator" | "unit" | "unknown";
|
||||
type NumberFormatPartTypes = ES2018NumberFormatPartType | ES2020NumberFormatPartType;
|
||||
|
||||
interface NumberFormatPart {
|
||||
type: ES2018NumberFormatPartType;
|
||||
type: NumberFormatPartTypes;
|
||||
value: string;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+14
-10
@@ -197,25 +197,24 @@ declare namespace Intl {
|
||||
): UnicodeBCP47LocaleIdentifier[];
|
||||
};
|
||||
|
||||
type ES2020NumberFormatPartType = ES2018NumberFormatPartType | "compact" | "exponentInteger" | "exponentMinusSign" | "exponentSeparator" | "unit" | "unknown";
|
||||
interface NumberFormatPart {
|
||||
type: ES2020NumberFormatPartType
|
||||
}
|
||||
|
||||
interface NumberFormatOptions {
|
||||
compactDisplay?: "short" | "long" | undefined;
|
||||
notation?: "standard" | "scientific" | "engineering" | "compact" | undefined;
|
||||
signDisplay?: "auto" | "never" | "always" | undefined;
|
||||
unit?: NumberFormatUnit | undefined;
|
||||
signDisplay?: "auto" | "never" | "always" | "exceptZero" | undefined;
|
||||
unit?: string | undefined;
|
||||
unitDisplay?: "short" | "long" | "narrow" | undefined;
|
||||
currencyDisplay?: string | undefined;
|
||||
currencySign?: string | undefined;
|
||||
}
|
||||
|
||||
interface ResolvedNumberFormatOptions {
|
||||
compactDisplay?: "short" | "long";
|
||||
notation?: "standard" | "scientific" | "engineering" | "compact";
|
||||
signDisplay?: "auto" | "never" | "always";
|
||||
unit?: NumberFormatUnit;
|
||||
signDisplay?: "auto" | "never" | "always" | "exceptZero";
|
||||
unit?: string;
|
||||
unitDisplay?: "short" | "long" | "narrow";
|
||||
currencyDisplay?: string;
|
||||
currencySign?: string;
|
||||
}
|
||||
|
||||
interface DateTimeFormatOptions {
|
||||
@@ -255,6 +254,10 @@ declare namespace Intl {
|
||||
}
|
||||
|
||||
interface Locale extends LocaleOptions {
|
||||
/** A string containing the language, and the script and region if available. */
|
||||
baseName: string;
|
||||
/** The primary language subtag associated with the locale. */
|
||||
language: string;
|
||||
/** Gets the most likely values for the language, script, and region of the locale based on existing values. */
|
||||
maximize(): Locale;
|
||||
/** Attempts to remove information about the locale that would be added by calling `Locale.maximize()`. */
|
||||
@@ -282,6 +285,7 @@ declare namespace Intl {
|
||||
};
|
||||
|
||||
interface DisplayNamesOptions {
|
||||
locale: UnicodeBCP47LocaleIdentifier;
|
||||
localeMatcher: RelativeTimeFormatLocaleMatcher;
|
||||
style: RelativeTimeFormatStyle;
|
||||
type: "language" | "region" | "script" | "currency";
|
||||
@@ -304,7 +308,7 @@ declare namespace Intl {
|
||||
*
|
||||
* [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of).
|
||||
*/
|
||||
of(code: string): string;
|
||||
of(code: string): string | undefined;
|
||||
/**
|
||||
* Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current
|
||||
* [`Intl/DisplayNames`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) object.
|
||||
|
||||
Vendored
+2
-3
@@ -17,8 +17,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
allSettled<T extends readonly unknown[] | readonly [unknown]>(values: T):
|
||||
Promise<{ -readonly [P in keyof T]: PromiseSettledResult<T[P] extends PromiseLike<infer U> ? U : T[P]> }>;
|
||||
allSettled<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>> }>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all
|
||||
@@ -26,5 +25,5 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
allSettled<T>(values: Iterable<T>): Promise<PromiseSettledResult<T extends PromiseLike<infer U> ? U : T>[]>;
|
||||
allSettled<T>(values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]>;
|
||||
}
|
||||
|
||||
Vendored
+1
@@ -2,3 +2,4 @@
|
||||
/// <reference lib="es2021.promise" />
|
||||
/// <reference lib="es2021.string" />
|
||||
/// <reference lib="es2021.weakref" />
|
||||
/// <reference lib="es2021.intl" />
|
||||
|
||||
Vendored
+9
@@ -8,6 +8,15 @@ declare namespace Intl {
|
||||
fractionalSecondDigits?: 0 | 1 | 2 | 3 | undefined;
|
||||
}
|
||||
|
||||
interface ResolvedDateTimeFormatOptions {
|
||||
formatMatcher?: "basic" | "best fit" | "best fit";
|
||||
dateStyle?: "full" | "long" | "medium" | "short";
|
||||
timeStyle?: "full" | "long" | "medium" | "short";
|
||||
hourCycle?: "h11" | "h12" | "h23" | "h24";
|
||||
dayPeriod?: "narrow" | "short" | "long";
|
||||
fractionalSecondDigits?: 0 | 1 | 2 | 3;
|
||||
}
|
||||
|
||||
interface NumberFormat {
|
||||
formatRange(startDate: number | bigint, endDate: number | bigint): string;
|
||||
formatRangeToParts(startDate: number | bigint, endDate: number | bigint): NumberFormatPart[];
|
||||
|
||||
Vendored
+8
-1
@@ -19,5 +19,12 @@ interface PromiseConstructor {
|
||||
* @param values An array or iterable of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
any<T>(values: (T | PromiseLike<T>)[] | Iterable<T | PromiseLike<T>>): Promise<T>
|
||||
any<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;
|
||||
|
||||
/**
|
||||
* The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
|
||||
* @param values An array or iterable of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
any<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>
|
||||
}
|
||||
|
||||
Vendored
+103
@@ -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;
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/// <reference lib="es2021" />
|
||||
/// <reference lib="es2022.array" />
|
||||
/// <reference lib="es2022.error" />
|
||||
/// <reference lib="es2022.object" />
|
||||
/// <reference lib="es2022.string" />
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
interface ErrorOptions {
|
||||
cause?: Error;
|
||||
}
|
||||
|
||||
interface Error {
|
||||
cause?: Error;
|
||||
}
|
||||
|
||||
interface ErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): Error;
|
||||
(message?: string, options?: ErrorOptions): Error;
|
||||
}
|
||||
|
||||
interface EvalErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): EvalError;
|
||||
(message?: string, options?: ErrorOptions): EvalError;
|
||||
}
|
||||
|
||||
interface RangeErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): RangeError;
|
||||
(message?: string, options?: ErrorOptions): RangeError;
|
||||
}
|
||||
|
||||
interface ReferenceErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): ReferenceError;
|
||||
(message?: string, options?: ErrorOptions): ReferenceError;
|
||||
}
|
||||
|
||||
interface SyntaxErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): SyntaxError;
|
||||
(message?: string, options?: ErrorOptions): SyntaxError;
|
||||
}
|
||||
|
||||
interface TypeErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): TypeError;
|
||||
(message?: string, options?: ErrorOptions): TypeError;
|
||||
}
|
||||
|
||||
interface URIErrorConstructor {
|
||||
new (message?: string, options?: ErrorOptions): URIError;
|
||||
(message?: string, options?: ErrorOptions): URIError;
|
||||
}
|
||||
|
||||
interface AggregateErrorConstructor {
|
||||
new (
|
||||
errors: Iterable<any>,
|
||||
message?: string,
|
||||
options?: ErrorOptions
|
||||
): AggregateError;
|
||||
(
|
||||
errors: Iterable<any>,
|
||||
message?: string,
|
||||
options?: ErrorOptions
|
||||
): AggregateError;
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
/// <reference lib="es2022" />
|
||||
/// <reference lib="dom" />
|
||||
/// <reference lib="webworker.importscripts" />
|
||||
/// <reference lib="scripthost" />
|
||||
/// <reference lib="dom.iterable" />
|
||||
Vendored
+8
@@ -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;
|
||||
}
|
||||
Vendored
+7
@@ -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;
|
||||
}
|
||||
Vendored
+42
-16
@@ -96,7 +96,7 @@ interface PropertyDescriptor {
|
||||
}
|
||||
|
||||
interface PropertyDescriptorMap {
|
||||
[s: string]: PropertyDescriptor;
|
||||
[key: PropertyKey]: PropertyDescriptor;
|
||||
}
|
||||
|
||||
interface Object {
|
||||
@@ -196,13 +196,13 @@ interface ObjectConstructor {
|
||||
|
||||
/**
|
||||
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
|
||||
* @param o Object on which to lock the attributes.
|
||||
* @param a Object on which to lock the attributes.
|
||||
*/
|
||||
freeze<T>(a: T[]): readonly T[];
|
||||
|
||||
/**
|
||||
* Prevents the modification of existing property attributes and values, and prevents the addition of new properties.
|
||||
* @param o Object on which to lock the attributes.
|
||||
* @param f Object on which to lock the attributes.
|
||||
*/
|
||||
freeze<T extends Function>(f: T): T;
|
||||
|
||||
@@ -300,7 +300,7 @@ declare var Function: FunctionConstructor;
|
||||
/**
|
||||
* Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter.
|
||||
*/
|
||||
type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;
|
||||
type ThisParameterType<T> = T extends (this: infer U, ...args: never) => any ? U : unknown;
|
||||
|
||||
/**
|
||||
* Removes the 'this' parameter from a function type.
|
||||
@@ -597,6 +597,23 @@ interface TemplateStringsArray extends ReadonlyArray<string> {
|
||||
interface ImportMeta {
|
||||
}
|
||||
|
||||
/**
|
||||
* The type for the optional second argument to `import()`.
|
||||
*
|
||||
* If your host environment supports additional options, this type may be
|
||||
* augmented via interface merging.
|
||||
*/
|
||||
interface ImportCallOptions {
|
||||
assert?: ImportAssertions;
|
||||
}
|
||||
|
||||
/**
|
||||
* The type for the `assert` property of the optional second argument to `import()`.
|
||||
*/
|
||||
interface ImportAssertions {
|
||||
[key: string]: string;
|
||||
}
|
||||
|
||||
interface Math {
|
||||
/** The mathematical constant e. This is Euler's number, the base of natural logarithms. */
|
||||
readonly E: number;
|
||||
@@ -928,7 +945,7 @@ interface RegExp {
|
||||
|
||||
// Non-standard extensions
|
||||
/** @deprecated A legacy feature for browser compatibility */
|
||||
compile(): this;
|
||||
compile(pattern: string, flags?: string): this;
|
||||
}
|
||||
|
||||
interface RegExpConstructor {
|
||||
@@ -1472,6 +1489,17 @@ interface Promise<T> {
|
||||
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively unwraps the "awaited type" of a type. Non-promise "thenables" should resolve to `never`. This emulates the behavior of `await`.
|
||||
*/
|
||||
type Awaited<T> =
|
||||
T extends null | undefined ? T : // special case for `null | undefined` when not in `--strictNullChecks` mode
|
||||
T extends object & { then(onfulfilled: infer F): any } ? // `await` only unwraps object types with a callable `then`. Non-object types are not unwrapped
|
||||
F extends ((value: infer V, ...args: any) => any) ? // if the argument to `then` is callable, extracts the first argument
|
||||
Awaited<V> : // recursively unwrap the value
|
||||
never : // the argument to `then` was not callable
|
||||
T; // non-object or non-thenable
|
||||
|
||||
interface ArrayLike<T> {
|
||||
readonly length: number;
|
||||
readonly [n: number]: T;
|
||||
@@ -1978,7 +2006,7 @@ interface Int8Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -2260,7 +2288,7 @@ interface Uint8Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -2542,7 +2570,7 @@ interface Uint8ClampedArray {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -2822,7 +2850,7 @@ interface Int16Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -3105,7 +3133,7 @@ interface Uint16Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -3387,7 +3415,7 @@ interface Int32Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -3668,7 +3696,7 @@ interface Uint32Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -3950,7 +3978,7 @@ interface Float32Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -4233,7 +4261,7 @@ interface Float64Array {
|
||||
* Sorts an array.
|
||||
* @param compareFn Function used to determine the order of the elements. It is expected to return
|
||||
* a negative value if first argument is less than second argument, zero if they're equal and a positive
|
||||
* value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.
|
||||
* value otherwise. If omitted, the elements are sorted in ascending order.
|
||||
* ```ts
|
||||
* [11,2,22,1].sort((a, b) => a - b)
|
||||
* ```
|
||||
@@ -4327,7 +4355,6 @@ declare namespace Intl {
|
||||
localeMatcher?: string | undefined;
|
||||
style?: string | undefined;
|
||||
currency?: string | undefined;
|
||||
currencyDisplay?: string | undefined;
|
||||
currencySign?: string | undefined;
|
||||
useGrouping?: boolean | undefined;
|
||||
minimumIntegerDigits?: number | undefined;
|
||||
@@ -4342,7 +4369,6 @@ declare namespace Intl {
|
||||
numberingSystem: string;
|
||||
style: string;
|
||||
currency?: string;
|
||||
currencyDisplay?: string;
|
||||
minimumIntegerDigits: number;
|
||||
minimumFractionDigits: number;
|
||||
maximumFractionDigits: number;
|
||||
|
||||
Vendored
+1
-1
@@ -1,2 +1,2 @@
|
||||
/// <reference lib="es2021" />
|
||||
/// <reference lib="es2022" />
|
||||
/// <reference lib="esnext.intl" />
|
||||
|
||||
Vendored
+4
-1
@@ -1,3 +1,6 @@
|
||||
declare namespace Intl {
|
||||
// Empty for now
|
||||
|
||||
interface DateTimeFormat {
|
||||
formatRange(startName: Date, endNumber: Date): string;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"es2019",
|
||||
"es2020",
|
||||
"es2021",
|
||||
"es2022",
|
||||
"esnext",
|
||||
// Host only
|
||||
"dom.generated",
|
||||
@@ -52,6 +53,10 @@
|
||||
"es2021.promise",
|
||||
"es2021.weakref",
|
||||
"es2021.intl",
|
||||
"es2022.array",
|
||||
"es2022.error",
|
||||
"es2022.object",
|
||||
"es2022.string",
|
||||
"esnext.intl",
|
||||
// Default libraries
|
||||
"es5.full",
|
||||
@@ -62,6 +67,7 @@
|
||||
"es2019.full",
|
||||
"es2020.full",
|
||||
"es2021.full",
|
||||
"es2022.full",
|
||||
"esnext.full"
|
||||
],
|
||||
"paths": {
|
||||
|
||||
Vendored
+367
-552
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user